집 >데이터 베이스 >MySQL 튜토리얼 >MySQL的sum函数返回的门类
MySQL的sum函数返回的类型 今天项目切换数据库时,出错 访问数据库的代码大概是这样: String sql = "select sum(number) as sumNumberOfOneDay from tableName";ListMap rows = getJdbcTemplate().queryForList(sql);for (Map row : rows) {SomeBean item =
MySQL的sum函数返回的类型String sql = "select sum(number) as sumNumberOfOneDay from tableName"; List<map> rows = getJdbcTemplate().queryForList(sql); for (Map row : rows) { SomeBean item = new SomeBean(); item.setSumNumberOfOneDay(objectToInt(row.get("sumNumberOfOneDay"))); } private int objectToInt(Object obj) { return Integer.parseInt("" + obj); }</map>
Connection conn = getJdbcTemplate().getDataSource().getConnection(); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(sql); ResultSetMetaData rsmd = rs.getMetaData(); for (int i = 1; i <br>DataBaseA打印的结果:<br>sumNumberOfOneDay, DECIMAL<br><br>DataBaseB打印的结果:<br>sumNumberOfOneDay, DOUBLE<br><br>基本可判断是MySQL的问题<br><br>网上搜索一下,果然:<br><pre name="code" class="java"> The SUM() and AVG() functions return a DECIMAL value for exact-value arguments (integer or DECIMAL), and a DOUBLE value for approximate-value arguments (FLOAT or DOUBLE). (Before MySQL 5.0.3, SUM() and AVG() return DOUBLE for all numeric arguments.)
if (obj instanceof Double) { return ((Double)obj).intValue(); } if (obj instanceof BigDecimal) { return ((BigDecimal)obj).intValue(); } return Integer.parseInt(obj.toString());
List<somebean> list = getJdbcTemplate().query(sql, new BeanPropertyRowMapper(SomeBean.class)); </somebean>
val = getString(columnIndex); if ((val != null) && (val.length() != 0)) { if ((val.indexOf("e") == -1) && (val.indexOf("E") == -1) && (val.indexOf(".") == -1)) { return Integer.parseInt(val); } else { // Convert floating point return (int) (Double.parseDouble(val)); } } else { return 0; }