我非常确定我正在关闭 finally 块中的 con,rs,stmt。但似乎在第 4 次尝试执行更新时出现“连接过多”错误。
public boolean setUserSettings(UserSettings userSettings)
{
ResultSet rs = null;
Connection con = null;
PreparedStatement stmt = null;
String _query;
try
{
System.out.println("total current connections: " + dataSource.getActive());
con = dataSource.getConnection();
_query = Util.readIn("/sql/select/selectUserSettingsCount.sql", MySqlPersistence.class);
stmt = con.prepareStatement(_query);
stmt.setString(1, userSettings.user);
rs = stmt.executeQuery();
boolean found = rs.next() && rs.getInt(1) == 1;
if (!found)
{
_query = Util.readIn("/sql/insert/setUserSettings.sql", MySqlPersistence.class);
stmt = con.prepareStatement(_query);
stmt.setString(1, userSettings.user);
stmt.setBoolean(2, userSettings.isActive);
stmt.setString(3, userSettings.phone);
stmt.setString(4, userSettings.phone2);
stmt.setString(5, userSettings.phone3);
stmt.setString(6, userSettings.contact_strategy);
}
else
{
_query = Util.readIn("/sql/update/updateUserSettings.sql", MySqlPersistence.class);
stmt = con.prepareStatement(_query);
stmt.setString(1, userSettings.phone);
stmt.setString(2, userSettings.phone2);
stmt.setString(3, userSettings.phone3);
stmt.setString(4, userSettings.user);
}
int success = stmt.executeUpdate();
if (found && success == 1)
{
return true;
}
else
{
return false;
}
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
finally
{
try { if (rs != null) System.out.println("closing rs"); rs.close(); } catch (SQLException e) { }
try { if (stmt != null) System.out.println("closing stmt"); stmt.close(); } catch (SQLException e) { }
try { if (con != null) System.out.println("closing con"); con.close(); } catch (SQLException e) { }
}
}