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)
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();
}
}
}