我有很多线程访问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