我有一个文本文件,它的大小不是很重(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"
答案 0 :(得分:1)
获取连接后,您还需要关闭它。不关闭连接会导致资源泄漏,这可能最终导致服务器拒绝连接,因为已达到最大连接数。
我建议您更改代码以使用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();
}
答案 1 :(得分:0)
完成流程后,请关闭声明和连接关闭:
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) {
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();
}
finally {
if (ps != null) try { ps .close(); } catch (SQLException logOrIgnore) {}
if (con != null) try { con .close(); } catch (SQLException logOrIgnore) {}
}
}