我正在尝试通过 MySQL 连接到存储在本地主机上的数据库,并且我正在尝试插入一个新语句,但我收到了一个我以前从未见过的奇怪错误。我不确定我的插入语句是否不正确,或者代码本身是否不正确。
我收到的错误是
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()
还要记住,完成后必须关闭语句和与数据库的连接。
关于java - 使用 JDBC 语句执行查询时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25705762/