我认为我的应用程序被诅咒了,debug随心所欲,我不知道为什么。逐行调试似乎还会分析注释的行。我认为问题出在我的连接方法上,我看到性能显著下降,在第三次(或第四次)nvm连接时,我得到了这个错误:
com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Too many connections我确信我每次访问数据库时都会关闭连接(在实现中使用try catch之外的finally语句)。
下面是我的connection类:
package Connection;
import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.rmi.RemoteException; import java.sql.*; import java.util.Properties;
public class ConnectionDB {
public static ResultSet rs = null;
public static Statement stat = null;
public static Connection cn = null;
public static void connect() throws RemoteException {
String dbHost="",dbUser="",dbPassword="";
Properties prop=new Properties();
try
{
//carico il file:
prop.load(new FileInputStream("***/config.properties"));
//Leggo le proprietà del file:
dbHost=prop.getProperty("host");
dbUser=prop.getProperty("user");
dbPassword=prop.getProperty("password");
}catch(FileNotFoundException fe){
System.out.println("config file not found");
}catch(IOException ex){
System.out.println("Error reading config file");
}
try
{
String driver = "com.mysql.jdbc.Driver";
Class.forName(driver);
dbHost = "jdbc:mysql://"+dbHost;
cn = DriverManager.getConnection(dbHost,dbUser,dbPassword);
stat = cn.createStatement();
}catch(SQLException e){
System.out.println("Can't connect to the DB");
}
catch(ClassNotFoundException cln){
System.out.println("Error using JDBC driver");
}
}
public static void disconnect() throws RemoteException {
try{
if(rs != null) rs.close();
if(stat != null) stat.close();
if(cn != null) cn.close();
}
catch(SQLException sqlEx){
System.out.println("Error: disconnect");
}
}
}发布于 2012-07-20 00:58:26
通常情况下,可供用户使用的连接数量有限。此外,建立连接的操作成本很高。因此,如果您遇到性能问题,您应该开始使用连接池、discussion about connection pools
关于你的代码,请确保你总是在finally块中释放连接。我们也不知道你运行的是哪种类型的查询。打印您的查询并尝试在mysql中手动运行它们,看看问题是否出在您的SQL上,而不是Java。此外,您永远不会关闭FileInputStream,这意味着您可能会用完文件处理程序。
如果您在循环中运行相同的语句,请考虑使用PreparedStatements和批处理更新和事务。如果您使用事务,请确保您没有太多处于未提交状态的数据。
如果想要分析查询的性能,可以使用JAMon (Java Application Monitor)
建议增加连接的数量类似于建议腹泻患者吃更多的食物。
发布于 2012-07-20 02:56:39
disconnect方法可能需要以下增强。在这个示例中,我们将分别关闭ResultSet、Statement和Connection。这将避免单个异常不会导致不关闭连接对象的情况。
public static void disconnect() throws RemoteException {
try{
if(rs != null) rs.close();
}
catch(SQLException sqlEx){
System.out.println("Error: disconnect");
}
try{
if(stat != null) stat.close();
}
catch(SQLException sqlEx){
System.out.println("Error: disconnect");
}
try{
if(cn != null) cn.close();
}
catch(SQLException sqlEx){
System.out.println("Error: disconnect");
}
}发布于 2012-07-19 23:39:04
我认为你可以尝试一下以下几个选项:
正如在提供的评论中所提供的,您可以increase the max number of connections allowed.
https://stackoverflow.com/questions/11564000
复制相似问题