問題描述
在使用 SUM 時,我在將 MySQL 查詢的結(jié)果轉(zhuǎn)換為 Java 類時遇到了一點問題.
I'm having a bit of a problem with converting the result of a MySQL query to a Java class when using SUM.
在 MySQL 中執(zhí)行簡單 SUM 時
When performing a simple SUM in MySQL
SELECT SUM(price) FROM cakes WHERE ingredient = 'chocolate';
price
是一個整數(shù),看起來 SUM
有時返回一個字符串,有時返回一個整數(shù),具體取決于 JDBC 驅(qū)動程序的版本.
with price
being an integer, it appears that the SUM
sometimes returns a string and sometimes an integer, depending on the version of the JDBC driver.
顯然,服務(wù)器確實告訴 JDBC 驅(qū)動程序 SUM
的結(jié)果是一個字符串,而 JDBC 驅(qū)動程序有時會方便地"將其轉(zhuǎn)換為整數(shù).(參見Marc Matthews 的解釋).
Apparently the server does tell the JDBC driver that the result of SUM
is a string, and the JDBC driver sometimes 'conveniently' converts this to an integer. (see Marc Matthews' explanation).
Java 代碼使用了一些 BeanInfo 和 內(nèi)省使用查詢結(jié)果自動填充(列表)bean.但是,如果部署應(yīng)用程序的服務(wù)器之間的數(shù)據(jù)類型不同,這顯然是行不通的.
The Java code uses some BeanInfo and Introspection to automagically fill in a (list of) bean(s) with the result of a query. But this obviously can't work if the datatypes differ between servers where the application is deployed.
我不在乎我得到的是字符串還是整數(shù),但我希望始終擁有相同的數(shù)據(jù)類型,或者至少提前知道我將獲得哪種數(shù)據(jù)類型.
I don't care wether I get a string or an integer, but I'd like to always have the same datatype, or at least know in advance which datatype I'll be getting.
有沒有辦法知道 MySQL SUM
從 Java 代碼中返回哪種數(shù)據(jù)類型?或者有誰知道更好的方法來解決這個問題?
Is there some way to know which datatype will be returned by a MySQL SUM
from within the Java code? Or does anyone know some better way to deal with this?
推薦答案
這只是一個猜測,但可能強制轉(zhuǎn)換為整數(shù)會迫使 MySQL 總是告訴它是一個整數(shù).
This is just a guess, but maybe casting to integer will force MySQL to always tell it is an integer.
SELECT CAST(SUM(price) AS SIGNED) FROM cakes WHERE ingredient = 'marshmallows';
這篇關(guān)于MySQL 中 SUM 結(jié)果的數(shù)據(jù)類型的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!