gpt4 book ai didi

java - 来自服务器的错误 : Data source rejected establishment of connection, 消息: "Too many connections"

转载 作者:行者123 更新时间:2023-11-29 00:11:52 24 4
gpt4 key购买 nike

我有一个文本文件,它的大小不是那么大 (600KB),我的代码应该读取这个文件并将整个包含内容发送到我的数据库:

    private static void readBigFileAndSendToDB() throws Exception {
Scanner s = new Scanner(new FileReader("tf1.txt"));
while (s.hasNextLine()) {
String eachLine = s.nextLine(); // each Line
sendBigFileToDB(eachLine);
} // (end of file).
System.out.println("Sent big file to DB");
s.close();
}


private static void sendBigFileToDB(String line) {
Connection con = null;
PreparedStatement ps = null;
String query = "Insert into BigFile(text) values ('" + line + "')";

try {
if (line != null) {
con = DriverManager.getConnection(...);
ps = con.prepareStatement(query);
ps.execute();
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}

但是当我运行程序时,出现了这个异常:

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Data source rejected establishment of connection,  message from server: "Too many connections"

最佳答案

当你获得一个连接时,你也需要关闭它。不关闭连接会导致资源泄漏,这最终可能会导致服务器拒绝连接,因为已达到最大连接数。

我建议您更改代码以使用 try-with-resources因此您的资源在使用范围结束时会自动关闭:

if (line == null) return;
String query = "Insert into BigFile(text) values (?)";

try (
Connection con = con = DriverManager.getConnection(...);
PreparedStatement ps = con.prepareStatement(query);
){
ps.setString(1, line);
ps.executeUpdate();
} catch (SQLException sqle) {
sqle.printStackTrace();
}

请注意,我还通过正确使用准备好的语句参数将您的 line 连接替换为查询。

您的代码可以通过将连接创建和语句准备移到您的 readBigFileAndSendToDB 中进一步改进,这样它只完成一次并且不会在每次迭代时产生开销:

String query = "Insert into BigFile(text) values (?)";

try (
Scanner s = new Scanner(new FileReader("tf1.txt"));
Connection con = con = DriverManager.getConnection(...);
PreparedStatement ps = con.prepareStatement(query);
){
while (s.hasNextLine()) {
String line = s.nextLine();
if (line == null) continue;
ps.setString(1, line);
ps.addBatch();
}
ps.executeBatch();
} catch (SQLException sqle) {
sqle.printStackTrace();
}

关于java - 来自服务器的错误 : Data source rejected establishment of connection, 消息: "Too many connections",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24693760/

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