2017-02-23 5 views
1

JavaからMySQLに接続するときにエラーが発生するので、接続設定をtryステートメントにラップしています。しかし、これは、その後Connection変数を使用しようとすると、variable conn might not have been initializedエラーがスローされることを意味します。 これを行う適切な方法は何ですか? は私が持っているもの:Java:try-catch MySQL例外

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

エラー:

> variable conn might not have been initialized 

答えて

0

あなたはこのようなあなたのオブジェクトを宣言する必要があります。

Connection conn = null; 

そして、あなたはそれを使用する前に、それがnullではないことを確認してください。

if (conn != null && !conn.isClosed()) { 
    conn.close(); 
} 
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 

コード:

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

また、あなたはのtry-と資源自動的に接続を閉じることができます使用することができます。

try (Connection conn = DriverManager.getConnection(CONNECTION_URL); 
PreparedStatement ps = con.prepareStatement(sqlStrQuery);){ 
     // execution code here.. 
    }catch(SQLException sqle){ 
     // do something 
    } 
1

変数conがのtry/catchの外側にアクセス可能ですが、コンパイラは、詐欺にもNULLでない値を割り当てることはないかもしれないことは可能であることを認識するのに十分なスマートです。ローカル変数はインスタンス変数のように自動的にヌルではありません。 これを解決する最も簡単な方法は変更することです。

Connection con = null; 

Connection con;