[英]NullPointerException while executing query using JDBC Statement
我試圖使用通過MySQL連接到存儲在localhost上的數據庫,並且試圖插入一條新語句,但是卻遇到了一個我從未見過的怪異錯誤。 我不確定我的插入語句是否錯誤或任何代碼本身是否錯誤。
我得到的錯誤是
Exception in thread "main" java.lang.NullPointerException
at DatabaseConnect.main(DatabaseConnect.java:24)
Java Result: 1
//
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DatabaseConnect {
public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
//start JDBC
try {
//Register JDBC driver
System.out.println("Connecting to Database...");
Class.forName("com.mysql.jdbc.Driver"); //connect using JDBC driver
System.out.println("Connection to driver Successful");
System.out.println("Connecting to Database");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/courseproject", "root", "root"); //connection to database
System.out.println("Connection to Database successful");
System.out.println("execute insert statement");
statement.execute("INSERT INTO courseproject.agent (AGT_ID, AGT_LNAME, AGT_FNAME, AGT_STREET, ADD_ZIP, AGT_PHONE, AGT_EMAIL, OFF_CODE) VALUES ('6', 'firstname', 'lastname', 'street address', '34398', '348374', 'sfhf@aol.com', '35464') ");
} catch(ClassNotFoundException error){
System.out.println("Error: " + error.getMessage());
}catch(SQLException error){
System.out.println("Error: " + error.getMessage());
}
}
}
語句未初始化。 您應該創建一個語句:
statement = connection.createStatement()
還請記住,完成后必須關閉語句並連接到數據庫。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.