我试图通过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());
}
}
}
答案 0 :(得分:2)
语句未初始化。你应该创建一个声明:
statement = connection.createStatement()
还要记住,完成后必须关闭语句和数据库连接。