1,useServerPrepStmts参数影响数据精度
- useServerPrepStmts:如果服务器支持,是否使用服务器端预处理语句? 默认值为“真”
com.mysql.jdbc.ResultSetImpl public BigDecimal getBigDecimal(int columnIndex) throws SQLException { if (!this.isBinaryEncoded) { // 1 String stringVal = this.getString(columnIndex); if (stringVal != null) { BigDecimal val; if (stringVal.length() == 0) { val = new BigDecimal(this.convertToZeroLiteralStringWithEmptyCheck()); return val; } else { try { val = new BigDecimal(stringVal); return val; } catch (NumberFormatException var5) { throw SQLError.createSQLException(Messages.getString("ResultSet.Bad_format_for_BigDecimal", new Object[]{stringVal, Constants.integerValueOf(columnIndex)}), "S1009"); } } } else { return null; } } else { return this.getNativeBigDecimal(columnIndex); // 2 } }
- Java在用BigDecimal接受数据库varchar数据时,会丢失精度
- mysql的url后面useServerPrepStmts参数 决定了截图中isBinaryEncoded的值
- 如果isBinaryEncoded为true,则代码会走2的逻辑,2的逻辑是读取数据库中decimal的保留位数,因为数据库价格那个字段是varchar,所以读取到的保留位数为0,最终导致获取的数据是不保留小数位
- 如果isBinaryEncoded为false,则走1的逻辑,1的逻辑是拿数据库里查询的数据直接构造bigdecimal并返回,所以不会出问题
- useServerPrepStmts = false& rewriteBatchedStatements = true
作者:JavaHub
链接:https://www.jianshu.com/p/86a01ee64080
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。