我有很多線程訪問MYSQL數據庫,起初我沒有使用連接池,所以我有這個錯誤「你不能操作一個關閉ResultSet「仍然有你使用連接池後無法操作關閉ResultSet錯誤
我在Google上搜索並發現我應該使用連接池,所以我嘗試使用c3p0 API來實現,但我仍然遇到同樣的問題並且沒有任何更改。 所以我應該同步getAllcountries方法或有另一個更好的解決方案。
public class DataSource {
private static DataSource datasource;
private ComboPooledDataSource cpds ;
private DataSource() throws IOException, SQLException, PropertyVetoException {
cpds = new ComboPooledDataSource();
cpds.setDriverClass("com.mysql.jdbc.Driver"); //loads the jdbc driver
cpds.setJdbcUrl("jdbc:mysql://localhost/question_game");
cpds.setUser("root");
cpds.setPassword("");
cpds.setMaxPoolSize(500);
}
public static DataSource getInstance() throws IOException, SQLException, PropertyVetoException {
if (datasource == null) {
datasource = new DataSource();
return datasource;
} else {
return datasource;
}
}
public Connection getConnection() throws SQLException {
return this.cpds.getConnection();
}
public List<Country> getAllCountries() {
String query = "SELECT * FROM country order by name ";
List<Country> list = new ArrayList<Country>();
Country country = null;
ResultSet rs = null;
try {
try {
connection = DataSource.getInstance().getConnection();
} catch (IOException e) {
e.printStackTrace();
} catch (PropertyVetoException e) {
e.printStackTrace();
}
statement = connection.createStatement();
rs = statement.executeQuery(query);
while (rs.next()) {
//getting countries
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
//DbUtil used to check if null
DbUtil.close(rs);
DbUtil.close(statement);
DbUtil.close(connection);
}
return list;
}
我正在使用getInstance()方法,因爲我只想要一個DataSource實例。 – Marah 2014-10-05 02:17:01
它不是正在關閉的數據源,而是從數據源獲得的連接正在被替換。 – 2014-10-05 07:53:15