2017-02-23 112 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; 

並確保它不爲空,你使用它之前:

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 (Connection conn = DriverManager.getConnection(CONNECTION_URL); 
PreparedStatement ps = con.prepareStatement(sqlStrQuery);){ 
     // execution code here.. 
    }catch(SQLException sqle){ 
     // do something 
    } 
1

變量con是在try/catch語句的外部訪問,但編譯器是足夠聰明的認識到,有可能是騙子可能永遠不會被分配一個值,即使不爲空。局部變量不像實例變量那樣自動爲空。 要解決的最簡單的事情就是改變。

Connection con; 

Connection con = null;