學習記錄:使用JDBC連線資料庫報NullPointerException。
阿新 • • 發佈:2021-02-09
最近在學習使用JDBC的過程中遇到了一個問題:mysql資料庫驅動連線成功,資料庫連線成功,資料庫中對應查詢有資料且SQL語句沒寫錯,但報了空指標異常。
1.異常程式碼如下:
// 異常程式碼
package trytousemysql;
import java.sql.*;
public class JDBCtest01 {
static Connection connection=null;
static Statement sql;
static ResultSet resultSet;
static String url;
static String user;
static String password;
public Connection connection_1() throws SQLException {
url="jdbc:mysql://localhost:3306/teaching";
user="root";
password="123456";
try {
Class.forName("com.mysql.cj.jdbc.Driver" );
System.out.println("mysql資料庫驅動載入成功");
connection=DriverManager.getConnection(url,user,password);
System.out.println("資料庫連線成功");
System.out.println(connection);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return connection;
}
public void update() throws SQLException {
try {
resultSet=sql.executeQuery("select * from teaching.student");
while (resultSet.next()){
System.out.println("更新前:");
String studentno=resultSet.getString("studentno");
String sname=resultSet.getString("sname");
String sex=resultSet.getString("sex");
String birthdate=resultSet.getString("birthdate");
String entrance=resultSet.getString("entrance");
String phone=resultSet.getString("phone");
String Email=resultSet.getString("Email");
System.out.println(studentno+" "+sname+" "+sex+" "+birthdate+" "+entrance+" "+phone+" "+Email);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
public static void main(String[] args) throws SQLException {
JDBCtest01 ctest01=new JDBCtest01();
ctest01.connection_1();
ctest01.update();
}
}
有如下異常:
2.原因是我在執行SQL語句前居然沒有將connection介面的createstatement方法建立的物件傳遞給statement即:沒有寫下statement sql=connection.creastatement;
3.總結:敲程式碼的時候要細心,要明白每個步驟的作用。不要漏了程式碼。吸取經驗教訓。>.<