問題描述
在使用 SUM 時,我在將 MySQL 查詢的結果轉換為 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 中執行簡單 SUM 時
When performing a simple SUM in MySQL
SELECT SUM(price) FROM cakes WHERE ingredient = 'chocolate';
price
是一個整數,看起來 SUM
有時返回一個字符串,有時返回一個整數,具體取決于 JDBC 驅動程序的版本.
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.
顯然,服務器確實告訴 JDBC 驅動程序 SUM
的結果是一個字符串,而 JDBC 驅動程序有時會方便地"將其轉換為整數.(參見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 和 內省使用查詢結果自動填充(列表)bean.但是,如果部署應用程序的服務器之間的數據類型不同,這顯然是行不通的.
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.
我不在乎我得到的是字符串還是整數,但我希望始終擁有相同的數據類型,或者至少提前知道我將獲得哪種數據類型.
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 代碼中返回哪種數據類型?或者有誰知道更好的方法來解決這個問題?
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?
推薦答案
這只是一個猜測,但可能強制轉換為整數會迫使 MySQL 總是告訴它是一個整數.
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';
這篇關于MySQL 中 SUM 結果的數據類型的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!