问题描述
- 帮帮忙,看看应该改哪里,谢谢
-
package javaJDBC;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;/*
- //采用PreparedStatement添加数据
*/
public class InsertTest02 {public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
try{
//加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//连接数据库
String dbUrl = "jdbc:mysql://localhost:3306/student";
String username = "root";
String password = "mysql";
//执行PreparedStatement语句,执行SQL
String name = "莫燕";
String number = "123456";
String class1 = "1102";
int score = 97;
String sql = "insert into stu(name, number, class1, scoree) values (?, ?, ?, ?)";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, number);
pstmt.setString(3, class1);
pstmt.setInt(4, score);
pstmt.executeUpdate();
System.out.println("添加员工成功");
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}finally{
try{
//关闭原则:从里到外
if(pstmt != null)
pstmt.close();
if(conn != null)
conn.close();
}catch(SQLException e){
e.printStackTrace();
}}
}
}
Exception in thread "main" java.lang.NullPointerException
at javaJDBC.InsertTest02.main(InsertTest02.java:29) - //采用PreparedStatement添加数据
解决方案
public static void main(String[] args) {
Connection conn = null;
PreparedStatement pstmt = null;
try{
//加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
//连接数据库
String dbUrl = "jdbc:mysql://localhost:3306/student";
String username = "root";
String password = "mysql";
//执行PreparedStatement语句,执行SQL
String name = "莫燕";
String number = "123456";
String class1 = "1102";
int score = 97;
String sql = "insert into stu(name, number, class1, scoree) values (?, ?, ?, ?)";
conn= DriverManager.getConnection(dbUrl, username, password); ------少了这一句
pstmt =conn.prepareStatement(sql);
pstmt.setString(1, name);
pstmt.setString(2, number);
pstmt.setString(3, class1);
pstmt.setInt(4, score);
pstmt.executeUpdate();
System.out.println("添加员工成功");
}catch(ClassNotFoundException e){
e.printStackTrace();
}catch(SQLException e){
e.printStackTrace();
}finally{
try{
//关闭原则:从里到外
if(pstmt != null)
pstmt.close();
if(conn != null)
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
解决方案二:
String sql = "insert into stu(name, number, class1, scoree) values (?, ?, ?, ?)";
是不是错了