Cannot invoke “java.sql.connection.preparestatement(string)” because “con” is null




Error description

Error message:

Cannot invoke “java.sql.Connection.prepareStatement(String)” because “con” is null.

Explanation:

This error occurs when you are trying to call the “prepareStatement” method on a null object reference “con”. The error message suggests that the variable “con” has not been initialized or is currently null.

Example:

Let’s assume you are trying to establish a database connection and perform some database operations:

// Step 1: Import the necessary classes
import java.sql.*;

class Main {
  public static void main(String[] args) {
    // Step 2: Create the connection object
    Connection con = null;
    
    try {
      // Step 3: Register the JDBC driver (if required)
      Class.forName("com.mysql.jdbc.Driver");
      
      // Step 4: Open a connection
      con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
      
      // Step 5: Perform database operations
      // Assuming you are trying to prepare a statement here
      PreparedStatement stmt = con.prepareStatement("SELECT * FROM customers");
      
      // Rest of your code to execute the prepared statement
    } catch(SQLException e) {
        e.printStackTrace();
    } catch(ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
      // Step 6: Close the connection (if required)
      try {
        if(con != null)
          con.close();
      } catch(SQLException e) {
        e.printStackTrace();
      }
    }
  }
}

In the provided example, we follow the standard JDBC connection steps. However, imagine that an exception occurs during the connection establishment, and the code jumps to the catch block without assigning any connection object to “con”. In such a scenario, if you try to call the “prepareStatement” method on “con” in the later part of the code, you will encounter the mentioned error since “con” is null.

To resolve this error, ensure that you properly initialize the “con” variable before calling any methods on it. Additionally, make sure that the connection is established successfully without any exceptions.


Read more

Leave a comment