我正在为多线程MySQL系统使用一些代码。它工作正常,将在不到半秒的时间内将条目放入我的数据库。我的问题是,我的程序成功连接和写入数据库的速度并不是很好。有些时候它会正常工作,有时我会收到这个错误,或者类似的错误:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 27,697 milliseconds ago. The last packet sent successfully to the server was 1 milliseconds ago.
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1121)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3670)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3559)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4110)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2570)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2731)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2815)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1379)
at MySQL.putEntry(MySQL.java:46)
at MySQL.main(MySQL.java:105)
Caused by: java.io.EOFException: Can not read response from server. Expected to read 4 bytes, read 0 bytes before connection was unexpectedly lost.
at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:3119)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3570)
... 9 more
我真的不确定为什么会这样?从一个地址执行太多语句? Anywho,这是我的代码:
private final ThreadedSQL sql;
private final DatabaseConnection connection;
private PreparedStatement statement;
public Hiscores() {
try {
loadConfig();
} catch (IOException e) {
e.printStackTrace();
}
sql = new ThreadedSQL(config);
connection = sql.getConnectionPool().nextFree();
}
public void putEntry(final Player player) {
try {
statement = connection.getConnection().prepareStatement(QUERY(player));
statement.execute();
statement.closeOnCompletion();
} catch(Exception e) {
e.printStackTrace();
}
}
我没有包含的代码是无关紧要的,使用java.sql.Connection。有谁知道为什么会这样?感谢。
答案 0 :(得分:0)
一旦完成,您应该关闭语句和连接,否则资源池可能会耗尽或您的连接可能超时。我建议从某个JDBC池获取新连接。几年前我曾经在servlet环境中使用proxool。如果你在J2EE中,那么应用服务器应该为你做,但你必须使用DataSource。