【发布时间】:2020-05-06 16:16:06
【问题描述】:
我正在尝试创建一个数据库连接并使用带有 JDBC 到 MYSQL 的准备好的语句进行更新。
我尝试稍微更改连接,并且必须将preparedStatement 类更改为静态,以免出错。但是,在运行应用程序时,我遇到了 NullPointerException 错误,而且我看不到我需要在哪里创建一个新对象。
目前,我收到一个错误:
线程“主”java.lang.NullPointerException 中的异常
在 Alter.main(Alter.java:12)
import java.sql.PreparedStatement;
import java.sql.SQLException;
public abstract class Alter {
public static void main(String[] args) throws SQLException {
String query = "INSERT INTO school.students (First_Name, Last_Name, Gender, Grade_Level, IEP, Disruptive_1to5_LowtoHigh, OffTask_1to5_LowtoHigh, Not_Responsible_1to5_LowtoHigh, Not_GetAlong_1to5_LowtoHigh) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement myStmt = Connection.prepareStatement(query);
myStmt.setString(1, "Chris");
myStmt.setString(2, "Johnson");
myStmt.setString(3, "Male");
myStmt.setString(4, "K");
myStmt.setString(5, "N");
myStmt.setInt(6, 1);
myStmt.setInt(7, 3);
myStmt.setInt(8, 5);
myStmt.setInt(9, 2);
myStmt.addBatch();
int[] result = myStmt.executeBatch();
System.out.println(result + " were added to the database.");
}
}
import java.sql.*;
public class Connection extends Alter {
{
try {
Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance();
}
catch (Exception ex) {
}
try {
batchInsertRecordsIntoTable();
} catch (SQLException e) {
System.out.println(e.getMessage());
}
}
final static void batchInsertRecordsIntoTable() throws SQLException {
{
try {
DriverManager.getConnection(
"jdbc:mysql://localhost:3306/school?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC",
"root", "");
System.out.println("Connection Successful");
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
}
public Statement createStatement() {
return null;
}
public static PreparedStatement prepareStatement(String query) {
return null;
}
}
【问题讨论】:
-
从不使用 `catch (Exception ex) { }` 至少记录异常
-
Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance()完全没有必要。由于 JDBC 自动加载驱动程序,即使Class.forName("com.mysql.cj.jdbc.Driver")在这种情况下也不是必需的。