我正在练习JDBC。对于数据库,我使用了MySql 8.0.18(MySql Workbench)。但是,当我尝试插入时间戳值时,出现了异常。
JDBC代码:
package jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class setupMySqlDatabase {
public static void main(String args[]) {
String url = "jdbc:mysql://127.0.0.1:3306/employee?serverTimezone=UTC";
String user = "JDBCUser";
String password = "JDBCUser";
try(Connection conn = DriverManager.getConnection(url, user, password);
Statement stmt = conn.createStatement()) {
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
stmt.executeUpdate("CREATE TABLE species ("
+ "id INTEGER PRIMARY KEY, "
+ "name VARCHAR(255), "
+ "num_acres DECIMAL)");
stmt.executeUpdate(
"CREATE TABLE animal ("
+ "id INTEGER PRIMARY KEY, "
+ "species_id integer, "
+ "name VARCHAR(255), "
+ "date_born TIMESTAMP)");
stmt.executeUpdate("INSERT INTO species VALUES (1, 'African Elephant', 7.5)");
stmt.executeUpdate("INSERT INTO species VALUES (2, 'Zebra', 1.2)");
stmt.executeUpdate("INSERT INTO animal VALUES (1, 1, 'Elsa', '2001−05−06 00:02:15')");
stmt.executeUpdate("INSERT INTO animal VALUES (2, 2, 'Zelda', '2002−08−15 09:12')");
stmt.executeUpdate("INSERT INTO animal VALUES (3, 1, 'Ester', '2002−09−09 10:36')");
stmt.executeUpdate("INSERT INTO animal VALUES (4, 1, 'Eddie', '2010−06−08 01:24')");
stmt.executeUpdate("INSERT INTO animal VALUES (5, 2, 'Zoe', '2005−11−12 03:44')");
}catch(Exception ex) {
ex.printStackTrace();
}
}
}
[当我运行此代码时,我遇到了异常。
com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Incorrect datetime value: '2001−05−06 00:02:15' for column 'date_born' at row 1
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:104)
at com.mysql.cj.jdbc.StatementImpl.executeUpdateInternal(StatementImpl.java:1335)
at com.mysql.cj.jdbc.StatementImpl.executeLargeUpdate(StatementImpl.java:2108)
at com.mysql.cj.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1245)
at jdbc.setupMySqlDatabase.main(setupMySqlDatabase.java:29)
我不知道为什么会发生此错误!
是破折号!使用简单的破折号,而不是破折号或破折号(如您所使用的)。您可能之前曾在文字处理器中输入过代码。
更改:
stmt.executeUpdate(
"INSERT INTO animal VALUES (1, 1, 'Elsa', '2001−05−06 00:02:15')")
至:
stmt.executeUpdate(
"INSERT INTO animal VALUES (1, 1, 'Elsa', '2001-05-06 00:02:15')")
您发现区别了吗?