学习了一下怎么连接数据库操作数据,遇见了一些问题,记录一下
报错:
代码语言:javascript复制Exception in thread "main" com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Incorrect date value: '1995' for column 'submission_date' at row 1
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:104)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1098)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1046)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1371)
at com.mysql.cj.jdbc.CallableStatement.executeLargeUpdate(CallableStatement.java:2545)
at com.mysql.cj.jdbc.CallableStatement.executeUpdate(CallableStatement.java:901)
at JdbcDemo.main(JdbcDemo.java:13)
查了半天发现sql语句添加得值没有加单引号
错误代码:
代码语言:javascript复制 String sql2 ="INSERT INTO runoob_tbl(runoob_title,runoob_author, submission_date)VALUES(1,2,2021-12-14);";
修改过后:
代码语言:javascript复制import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JdbcDemo {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_frank","root","root");
String sql2 ="INSERT INTO runoob_tbl(runoob_title,runoob_author, submission_date)VALUES('1','2','2021-12-14');";
PreparedStatement statement = connection.prepareCall(sql2);
statement.executeUpdate();
statement.close();
connection.close();
}
}
代码优化:各种异常往出抛
代码语言:javascript复制import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JdbcDemo {
public static void main(String[] args) {
Connection connection = null;
PreparedStatement statement = null;
String sql2 ="INSERT INTO runoob_tbl(runoob_title,runoob_author, submission_date)VALUES('1','2','2021-12-14');";
try {
Class.forName("com.mysql.cj.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test_frank","root","root");
statement = connection.prepareCall(sql2);
statement.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
finally {
try {
if(statement != null){
statement.close();
}
if(connection != null){
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}