0

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());
        }




    }

}
2
  • What error are you getting? Commented Sep 6, 2014 at 23:42
  • sorry, ive added the error in the question Commented Sep 6, 2014 at 23:44

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.