gpt4 book ai didi

java - java jdbc连接过多

转载 作者:行者123 更新时间:2023-11-30 02:29:08 25 4
gpt4 key购买 nike

错误:- 严重:空com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException:数据源拒绝建立连接,来自服务器的消息:“连接太多”代码如下所示

   try {
BufferedReader br=new BufferedReader(new FileReader(filename));
String line;
String tru="TRUNCATE `project`.`uploadtable`;";
try
{
Statement stmt = Dutil.getConnection().createStatement();



stmt.executeUpdate(tru);
}
catch(Exception e){}
try {
while((line=br.readLine())!=null){
String values[]=line.split("\t");
String[] splitStr = values[1].split(" ");


try {String sql="INSERT INTO `project`.`uploadtable`
(`empid`, `date`, `time`, `in_out_index`) VALUES
('"+values[0]+"', '"+splitStr[0]+"', '"+splitStr[1]+"',
'"+values[3]+"');";
PreparedStatement
pst=Dutil.getConnection().prepareStatement(sql);
pst.executeUpdate();
} catch (SQLException ex) {
System.out.println("Error");

Logger.getLogger(UploadFrame.class.getName()).log(Level.SEVERE,
null, ex);
}
} br.close();

this.dispose();
LogButtonFrame lbf=new LogButtonFrame();
lbf.clockinouttable();
JOptionPane.showMessageDialog(null,"Upload Complete");} catch
(IOException ex) {
Logger.getLogger(UploadFrame.class.getName()).log(Level.SEVERE,
null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(UploadFrame.class.getName()).log(Level.SEVERE,
null, ex);
}
catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error");
}

最佳答案

问题是:

PreparedStatement pst = Dutil.getConnection().prepareStatement(sql);

您尚未显示 Dutil 的代码,但假设它在每次调用时创建一个新连接,这意味着该连接不会关闭,只能靠运气、驱动程序实现细节以及垃圾收集器将其关闭。

您应该使用 try-with-resources :

try (Connection connection = Dutil.getConnection();
PreparedStatement pst = connection.prepareStatement(sql)) {
// Use pst
}

此 block 结束后,pstconnection都会正确关闭,即使发生异常等情况。

关于java - java jdbc连接过多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44720597/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com