简体   繁体   中英

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.

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. So you are effectively trying to insert a string value into a DOUBLE column. Normally MySQL will auto convert strings to doubles, however, my suspicion is that at least some of your getPrice() values are not valid doubles. 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. LONGBLOB is not meant for this.

The data that is truncated is actually the price you're trying to insert into the DOUBLE column. If getPrice() is returning a string, you need to check decimal and thousant separators. MySQL uses . (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. FLOAT and DOUBLE may not be exact.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM