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) {}
}
}
?serverTimezone=Asia/Taipei。com.mysql.cj.jdbc.Driver。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 簡化資源管理。