【发布时间】:2014-05-01 13:07:43
【问题描述】:
我创建了一个应用程序,它每 5 分钟将数据写入数据库。
但是一段时间后会出现此错误:
Error: Data source rejected establishment of connection, message from server: "Too many connections"
我一直在搜索并告诉您在每次请求后关闭与数据库的连接。
我试过这个:
conexao.close();
但它给了我这个错误:
No operations allowed after conection closed.
如果问题表述不当,我深表歉意。
感谢您的帮助
----------我试过但没用的------ ---------
添加
finally{
if(conexao!=null)
conexao.close();
}
Class.forName("com.mysql.jdbc.Driver");
Connection conexao = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/bdTeste", "root", "root");
Statement stm = conexao.createStatement();
BufferedReader reader = new BufferedReader(new FileReader("C:/Users/RPR1BRG/Desktop/test.txt"));
String dados[] = new String[6];
String linha = reader.readLine();
while (linha != null) {
StringTokenizer st = new StringTokenizer(linha, ";\"");
dados[0] = st.nextToken();
dados[1] = st.nextToken();
dados[2] = st.nextToken();
dados[3] = st.nextToken();
dados[4] = st.nextToken();
dados[5] = st.nextToken();
DateFormat dateFormat = new SimpleDateFormat("d-M-yy");
PreparedStatement stmt = (PreparedStatement) conexao.prepareStatement("replace into registos"
+ " (data_registo, hora_registo, IdSensor, Temperatura, Humidade, pt_orvalho) values (?,?,?,?,?,?)");
try {
stmt.setDate(1, new java.sql.Date(dateFormat.parse(dados[0]).getTime()));
stmt.setString(2, dados[1]);
stmt.setString(3, dados[2]);
stmt.setString(4, dados[3]);
stmt.setString(5, dados[4]);
stmt.setString(6, dados[5]);
} catch (java.text.ParseException ex) {
Exceptions.printStackTrace(ex);
}
stmt.executeUpdate();
linha = reader.readLine();
PrintWriter writer = new PrintWriter("C:/Users/RPR1BRG/Desktop/test.txt");
writer.print("");
writer.close();
Verifica();
}
} catch (ClassNotFoundException | SQLException | IOException e) {
System.err.println("Erro: " + e.getMessage());
}finally{
if(conexao!=null)
conexao.close();
}
【问题讨论】:
-
这段代码被调用了多少次?我怀疑你在没有关闭它们的情况下创建了很多连接
-
感谢回复:我每 5 分钟调用一次此代码以读取文件并写入数据库。我试图关闭连接,但给了我另一个错误:“连接关闭后不允许任何操作。”