- useServerPrepStmts:如果服務(wù)器支持,是否使用服務(wù)器端預(yù)處理語句匾竿? 默認(rèn)值為“真”
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接受數(shù)據(jù)庫varchar數(shù)據(jù)時,會丟失精度
- mysql的url后面useServerPrepStmts參數(shù) 決定了截圖中isBinaryEncoded的值
- 如果isBinaryEncoded為true绰沥,則代碼會走2的邏輯篱蝇,2的邏輯是讀取數(shù)據(jù)庫中decimal的保留位數(shù),因為數(shù)據(jù)庫價格那個字段是varchar徽曲,所以讀取到的保留位數(shù)為0态兴,最終導(dǎo)致獲取的數(shù)據(jù)是不保留小數(shù)位
- 如果isBinaryEncoded為false,則走1的邏輯疟位,1的邏輯是拿數(shù)據(jù)庫里查詢的數(shù)據(jù)直接構(gòu)造bigdecimal并返回瞻润,所以不會出問題