首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

JDBC PreparedStatement 遺漏 Connection 導致 NullPointerException

     編輯:程式設計綜合問答

錯誤現象

Exception in thread "main" java.lang.NullPointerException
    at javaJDBC.InsertTest02.main(InsertTest02.java:29)

程式碼中直接呼叫 conn.prepareStatement(sql),但 conn 為 null。

程式碼問題分析

Connection conn = null;
// ... 載入驅動 ...
// 缺少:conn = DriverManager.getConnection(dbUrl, username, password);
PreparedStatement pstmt = conn.prepareStatement(sql); // NPE

修正程式碼

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";
        
        // 關鍵:建立連線
        conn = DriverManager.getConnection(dbUrl, username, password);
        
        String sql = "INSERT INTO stu(name, number, class1, score) VALUES (?, ?, ?, ?)";
        pstmt = conn.prepareStatement(sql);
        pstmt.setString(1, "莫燕");
        pstmt.setString(2, "123456");
        pstmt.setString(3, "1102");
        pstmt.setInt(4, 97);
        
        int rows = pstmt.executeUpdate();
        System.out.println("新增 " + rows + " 筆資料成功");
        
    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    } finally {
        // 關閉資源:先開後關
        try { if (pstmt != null) pstmt.close(); } catch (SQLException ignore) {}
        try { if (conn != null) conn.close(); } catch (SQLException ignore) {}
    }
}

關鍵檢查清單

  1. DriverManager.getConnection:務必在建立 Statement/PreparedStatement 前呼叫。
  2. 資料庫 URL 格式:MySQL 8.0+ 建議加時區 ?serverTimezone=Asia/Taipei。
  3. 驅動類別名稱:MySQL 8.0 為 com.mysql.cj.jdbc.Driver。
  4. 資源關閉順序:ResultSet → Statement → Connection。
  5. try-with-resources (Java 7+):自動關閉資源,程式碼更簡潔:
try (Connection conn = DriverManager.getConnection(url, user, pass);
     PreparedStatement pstmt = conn.prepareStatement(sql)) {
    pstmt.setString(1, "值");
    pstmt.executeUpdate();
} catch (SQLException e) {
    e.printStackTrace();
}

常見補充錯誤

  • Communications link failure:資料庫未啟動、防火牆阻擋、IP/Port 錯誤。
  • Access denied for user:帳密錯誤、權限不足、主機名稱不符。
  • Table doesn't exist:資料庫/資料表名稱大小寫敏感 (Linux)。

補上 DriverManager.getConnection 即可解決 NPE,並建議採用 try-with-resources 簡化資源管理。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved