The error message “cannot invoke ‘java.sql.Connection.prepareStatement(String)’ because ‘con’ is null” means that the object ‘con’ (which is of the java.sql.Connection type) is not assigned a valid value before calling the ‘prepareStatement’ method on it. In other words, ‘con’ is null, and you are trying to invoke a method on a null object reference, which leads to the error.
To fix this issue, you need to ensure that ‘con’ is properly initialized with a connection to the database before calling the ‘prepareStatement’ method. Here’s an example on how to do that:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Example {
public static void main(String[] args) {
// Initialize connection variables
String url = "jdbc:mysql://localhost:3306/database_name";
String username = "your_username";
String password = "your_password";
// Define connection object
Connection con = null;
try {
// Establish connection
con = DriverManager.getConnection(url, username, password);
// Use the connection to execute statements
PreparedStatement stmt = con.prepareStatement("SELECT * FROM table_name");
// ... rest of the code ...
// Close resources
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// Close the connection
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
In this example, we first initialize the connection variables such as the database URL, username, and password. Then, we declare a Connection object ‘con’ and assign it a null value. Inside the ‘try’ block, we establish a connection to the database using the DriverManager.getConnection() method, passing in the URL, username, and password. After that, we can proceed with preparing and executing the statements.
Remember to close the PreparedStatement and Connection objects in the appropriate places to release any resources held by them. In the ‘finally’ block, we check if the ‘con’ object is not null before closing it to avoid a potential NullPointerException.
This is just a basic example, and the actual implementation may vary depending on the specific database and requirements. Make sure to replace ‘database_name’, ‘your_username’, and ‘your_password’ with the actual values relevant to your setup.