我是Java初學者,但我認爲在使用try-catch-finally時,我不必使用throws SQLException
來聲明異常。但是,如果我不使用它的編譯器給我的錯誤:try-catch-finally在Java中拋出異常問題
"unreported exception java.sql.SQLException; must be caught or declare to be thrown".
我包括一個catch所以我不知道爲什麼這樣的錯誤發生。
public static ResultSet getResultSet (String query)
{
dbConn = getConnection();
try
{
stmt = dbConn.createStatement();
ResultSet rs = stmt.executeQuery(query);
return rs;
}
catch (SQLException ex)
{
return null;
}
finally
{
stmt.close();
dbConn.close();
}
}
幫助,很多小貓死亡。您已將'dbConn'和'stmt'聲明爲'static'。這段代碼絕對不是線程安全的。我強烈建議重做基本的Java和JDBC教程。 – BalusC 2010-08-11 18:48:11
當您使用ResultSet時,您也將獲得'SQLExceptions',因此您不妨傳播異常。連接關閉後,ResultSet可能不起作用。你可能想考慮執行周圍的習語。 http://stackoverflow.com/questions/341971/what-is-the-execute-around-idiom – 2010-08-11 19:10:46
FWIW:* normal *練習是將ResultSet映射到'List'並返回。對於某些示例,[head here](http://stackoverflow.com/questions/3148092/java-jdbc-mysql-connector-how-to-resolve-disconnection-after-a-long-idle-time/3148857#3148857 )和[這裏](http://stackoverflow.com/questions/1813858/sqlite-3-jdbc-driver-throws-resultsset-closed-exception-on-empty-resultset/1814443#1814443)。 –
BalusC
2010-08-11 19:14:03