1

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

3 Answers 3

1

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;
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0
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
    }

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.