我有一个 Excel 工作表 Book.xls
如下所示:
_________________________________________________________________
| | |
| INVOICE | INVOICE_DATE |
|_________________________________________|______________________|
| | |
|C-EDGE/SBI//BHO/(ATM)-013/2012–2013 | 11-Feb-2013 |
|_________________________________________|______________________|
|C-EDGE/SBI//BANG/(ATM)-013/2012–2013 | 13-Aug-2014 |
|_________________________________________|______________________|
我正在尝试将日期从 Excel 插入 MySQL 表,如下所示:
try {
POIFSFileSystem fs = new POIFSFileSystem(input);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
Row row;
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
row = sheet.getRow(i);
RichTextString CEDGE_INVOICE_NUMBER = row.getCell(0).getRichStringCellValue();
Date INVOICE_DATE = row.getCell(1).getDateCellValue();
System.out.println(INVOICE_DATE);
String sql = "INSERT INTO tablename VALUES('" + CEDGE_INVOICE_NUMBER + "','" + INVOICE_DATE + "')";
pstm = (PreparedStatement) con.prepareStatement(sql);
pstm.execute();
System.out.println("Import rows " + i);
}
con.commit();
pstm.close();
con.close();
input.close();
System.out.println("Success import excel to mysql table");
} catch (ClassNotFoundException e) {
System.out.println(e);
} catch (SQLException ex) {
System.out.println(ex);
} catch (IOException ioe) {
System.out.println(ioe);
}
但是,我有一个异常(exception):
"com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: 'Mon Feb 11 00:00:00 IST 2013' for column 'INVOICE_DATE' at row 1".
这是怎么造成的,如何解决?
最佳答案
使用PreparedStatement
时,使用?
占位符作为值;然后您可以使用PreparedStatemet的setDate方法。例如。在您的代码中:
String sql ="INSERT INTO tablename VALUES(?,?)";
pstm = (PreparedStatement) con.prepareStatement(sql);
for(int i=1; i<=sheet.getLastRowNum(); i++){
row = sheet.getRow(i);
RichTextString CEDGE_INVOICE_NUMBER = row.getCell(0).getRichStringCellValue();
String stringInvoiceNumber = ... // convert RichTextString to normal String
Date INVOICE_DATE = row.getCell(1).getDateCellValue();
// you have to use java.sql.Date instead of java.util.Date in PreparedStatement
java.sql.Date sqlInvoiceDate = new java.sql.Date(INVOICE_DATE.getTime());
pstm.setString(1, stringInvoiceNumber);
pstm.setDate(2, sqlInvoiceDate);
pstm.execute();
...
}
参见例如http://tutorials.jenkov.com/jdbc/preparedstatement.html了解更多信息。
关于java - com.mysql.jdbc.MysqlDataTruncation : Data truncation: Incorrect datetime value: 'Mon Feb 11 00:00:00 IST 2013' for column 'INVOICE_DATE' at row 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30612735/