向MySQL服务器发送Double值时出现SQL语法错误,求解决方案
解决MySQL插入Double类型时的语法错误问题
错误原因
你代码里用了String.format的%a格式符来格式化Double类型的rate值,这个格式符会将浮点数转换为十六进制浮点表示(比如5.0会被格式化为0x1.4p1,截断后可能出现.8p1这类MySQL无法识别的语法),直接拼到SQL语句里就会触发语法错误。
快速修复方案
把格式化Double值的%a替换为%f(固定小数位)或%g(自动选择简洁格式),同时SQL里的字符串建议用单引号(MySQL标准写法):
public static void sendDescription(Description description, int table_id){ Statement statement = null; try{ statement = connection.createStatement(); System.out.println(description.getId()); System.out.println(description.getRate()); // 把%a改成%f,字符串用单引号 String query = String.format("insert into descriptions (id, rate, description, name) " + "values (%d, %f, '%s', '%s')", description.getId(), description.getRate(), description.getDesctiption(), description.getName()); statement.executeUpdate(query); } catch (SQLException ex){ ex.printStackTrace(); } }
更安全规范的方案:使用PreparedStatement
直接拼接SQL字符串不仅容易出现类型格式问题,还存在SQL注入风险,推荐使用PreparedStatement,它会自动处理数据类型转换,无需手动格式化:
public static void sendDescription(Description description, int table_id){ PreparedStatement pstmt = null; try{ // 使用占位符?代替直接拼接值 String query = "insert into descriptions (id, rate, description, name) values (?, ?, ?, ?)"; pstmt = connection.prepareStatement(query); // 按顺序设置参数类型 pstmt.setInt(1, description.getId()); pstmt.setDouble(2, description.getRate()); pstmt.setString(3, description.getDesctiption()); pstmt.setString(4, description.getName()); pstmt.executeUpdate(); } catch (SQLException ex){ ex.printStackTrace(); } finally { // 务必关闭资源,避免连接泄漏 try { if (pstmt != null) pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } }
这种方式既解决了Double类型的格式问题,又提升了代码的安全性和可维护性,同时数据库可以预编译SQL语句,重复执行时性能更优。
内容的提问来源于stack exchange,提问作者Kiryl Vinahradau
相关产品推荐
相关产品推荐

