如何解决在 PreparedStatement 中获取 NullPointerException
所以我应该使用 MysqL 连接到 JDBC。 我有一个连接功能,它告诉我它工作正常。但是我在 PreparedStatement 代码中遇到了问题。
我的实际代码没有显示任何错误,但是当我运行时,我的终端显示“数据库连接成功”,然后给我“线程“main”中的异常java.lang.NullPointerException”。
这将我引导到我的行 -- PreparedStatement Posted = conn.prepareStatement("INSERT INTO people(firstName,lastName) VALUES ('"+var1+"','"+var2+"')")
所以在运行我的 post() 时会断开连接;这对我来说没有任何意义......我应该检查什么来解决这个问题?
public static void main(String[] args) throws Exception{
People project = new People();
project.createConnection();
project.post();
}
void createConnection(){
try {
String driver = "com.MysqL.cj.jdbc.Driver";
Class.forName(driver);
java.sql.Connection conn = DriverManager.getConnection("jdbc:MysqL://localhost:3306/peopledb","root","root");
if(conn != null){System.out.println("Database connection success");}
} catch (ClassNotFoundException ex) {
Logger.getLogger(People.class.getName()).log(Level.SEVERE,null,ex);
} catch (sqlException ex) {
Logger.getLogger(People.class.getName()).log(Level.SEVERE,ex);
}
}
void post() {
try {
final String var1 = "John";
final String var2 = "Doe";
PreparedStatement posted = conn.prepareStatement("INSERT INTO people(firstName,'"+var2+"')");
posted.executeUpdate();
if(conn != null){
System.out.println("Insert Completed");
}
} catch (sqlException ex) {
Logger.getLogger(People.class.getName()).log(Level.SEVERE,ex);
}
}
}
解决方法
您可以尝试以下修改来解决此特定问题。
public static void main(String[] args) throws Exception{
People project = new People();
project.createConnection();
project.post();
}
private java.sql.Connection conn; //create attribute accessible by both methods
void createConnection(){
try {
String driver = "com.mysql.cj.jdbc.Driver";
Class.forName(driver);
//assign value to attribute instead of local variable
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/peopledb","root","root");
if(conn != null){System.out.println("Database connection success");}
} catch (ClassNotFoundException ex) {
Logger.getLogger(People.class.getName()).log(Level.SEVERE,null,ex);
} catch (SQLException ex) {
Logger.getLogger(People.class.getName()).log(Level.SEVERE,ex);
}
}
void post() {
try {
final String var1 = "John";
final String var2 = "Doe";
//Below is prone to SQL Injection.
//PreparedStatement posted = conn.prepareStatement("INSERT INTO people(firstName,lastName) VALUES ('"+var1+"','"+var2+"')");
//Recommended approach
PreparedStatement posted = conn.prepareStatement("INSERT INTO people(firstName,lastName) VALUES (?,?)");
posted.setString(1,var1);
posted.setString(2,var2);
//we expect 1 row to inserted from this statement and executeUpdate
//will return the number of affected rows
if(posted.executeUpdate() ==1){
System.out.println("Insert Completed");
}
} catch (SQLException ex) {
Logger.getLogger(People.class.getName()).log(Level.SEVERE,ex);
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。