[英]Mysql in Java: Data truncated for column 'AAL' at row 1 error
I am trying to insert data from ArrayLists into a mysql table in Java, however I keep getting the following error: java.sql.SQLException: Data truncated for column 'AAL' at row 1. 我正在尝试将ArrayLists中的数据插入Java中的mysql表中,但是仍然出现以下错误:java.sql.SQLException:第1行的'AAL'列的数据被截断了。
Here is some of the code: 这是一些代码:
stmt = conn.createStatement();
sql = "CREATE TABLE IF NOT EXISTS stocks "
+ "(id INTEGER not NULL AUTO_INCREMENT, date LONGBLOB , " + "time LONGBLOB, "
+ " PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
for (int i = 0; i < stockList.size(); i++) {
System.out.println(stockList.get(i).getName() + i);
sql = "ALTER TABLE stocks ADD " + stockList.get(i).getName() + " DOUBLE";
stmt.executeUpdate(sql);
}
for (int i = 0; i < stockList.size(); i++) {
System.out.println(i);
sql = "INSERT INTO stocks (id, date, time, " + stockList.get(i).getName() + ") VALUES (NULL, '" + stockList.get(i).getDate() +
"', '" + stockList.get(i).getTime() + "', '" + stockList.get(i).getPrice() + "')";
stmt.executeUpdate(sql);
}
Any help is much appreciated. 任何帮助深表感谢。
You indicated that stockList.get(i).getPrice()
is a string, and you are putting quotes around the value in the insert. 您指出
stockList.get(i).getPrice()
是一个字符串,并且您要在插入值中加上引号。 So you are effectively trying to insert a string value into a DOUBLE column. 因此,您实际上是在尝试将字符串值插入DOUBLE列。 Normally MySQL will auto convert strings to doubles, however, my suspicion is that at least some of your getPrice() values are not valid doubles.
通常,MySQL会自动将字符串转换为双精度型,但是,我怀疑至少您的某些getPrice()值不是有效的双精度型。 You can try this instead:
您可以尝试以下方法:
... "', " + Double.parseDouble(stockList.get(i).getPrice()) + ")";
..but if some of the prices are not valid doubles, this will fail as well. ..但如果某些价格不是有效的双倍价格,也会失败。
There are some issues with your table and query design: 您的表和查询设计存在一些问题:
Use DATE
, TIME
, or DATETIME
types for storing dates and times. 使用
DATE
, TIME
或DATETIME
类型存储日期和时间。 LONGBLOB
is not meant for this. LONGBLOB
并非为此目的。
The data that is truncated is actually the price you're trying to insert into the DOUBLE
column. 截断的数据实际上是您要插入
DOUBLE
列中的价格。 If getPrice()
is returning a string, you need to check decimal and thousant separators. 如果
getPrice()
返回一个字符串,则需要检查小数点和千分号分隔符。 MySQL uses . MySQL使用。 (point) as decimal and , (comma) as thousant separator by default.
(点)默认为小数,而(逗号)为分隔符。 And do not use quotes in your query.
并且不要在查询中使用引号。
When dealing with prices, consider using DECIMAL
as type. 处理价格时,请考虑使用
DECIMAL
作为类型。 FLOAT
and DOUBLE
may not be exact. FLOAT
和DOUBLE
可能不正确。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.