Reputation: 39
I'm encountering errors when connecting to MySQL from Java, so I'm wrapping the connection establishment in a try
statement. However, doing this means that any attempt to use the Connection
variable afterwards throws a variable conn might not have been initialized
error.
What is the proper way to do this?
What I have:
Connection conn;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database", "alexis","pass");
}
catch (SQLException e) {
System.err.println("SQL exception: " + e.getMessage());
System.exit(1);
}
if (!conn.isClosed()) {
conn.close();
}
Error:
> variable conn might not have been initialized
Upvotes: 1
Views: 5630
Reputation: 31895
Connection conn; //was declared without initializing any value. You encountered error when try to use an uninitialized connection instance
Connection conn = null; // declared & initialized
Code:
Connection conn = null; // initialize conn with null value
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database", "alexis","pass");
}
catch (SQLException e) {
System.err.println("SQL exception: " + e.getMessage());
System.exit(1);
}
finally{
if (conn !=null && !conn.isClosed()) { // validate conn whether it is null
conn.close();
}
}
Alternatively, you can use try-with-resources which can close connection automatically.
try (Connection conn = DriverManager.getConnection(CONNECTION_URL);
PreparedStatement ps = con.prepareStatement(sqlStrQuery);){
// execution code here..
}catch(SQLException sqle){
// do something
}
Upvotes: 0
Reputation: 121
The variable con is accessible outside of the try/catch but the compiler is smart enough to recognize that it is possible that con might never be assigned a value, not even null. Local variables are not automatically null like instance variables. The easiest thing to address that is to change.
Connection con;
to
Connection con = null;
Upvotes: 1
Reputation: 2623
You should declare your object like this:
Connection conn = null;
And then make sure it's not null before you use it:
if (conn != null && !conn.isClosed()) {
conn.close();
}
Upvotes: 0