Reputation: 755
I am trying to use connect to a database stored on localhost via MySQL and I am trying to insert a new statement but I am getting a weird error that I've never seen before. I am unsure if my insert statement is incorrect or if any of the code itself is incorrect.
The error I am getting is
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', '[email protected]', '35464') ");
} catch(ClassNotFoundException error){
System.out.println("Error: " + error.getMessage());
}catch(SQLException error){
System.out.println("Error: " + error.getMessage());
}
}
}
Upvotes: 0
Views: 3043
Reputation: 380
statement is not initialized. You should create a statement :
statement = connection.createStatement()
Remever also that you have to close statement and connection to the database after you are done.
Upvotes: 2