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并返回,所以不会出问题
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容