简体   繁体   中英

NullPointerException while executing query using JDBC Statement

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', 'sfhf@aol.com', '35464') ");
        } catch(ClassNotFoundException error){
            System.out.println("Error: " + error.getMessage());

        }catch(SQLException error){
            System.out.println("Error: " + error.getMessage());
        }




    }

}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM