gpt4 book ai didi

java - java连接MySQL数据库

转载 作者:行者123 更新时间:2023-11-30 00:58:53 25 4
gpt4 key购买 nike

我正在使用一些用于多线程 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

我真的不知道为什么会发生这种情况?从一个地址执行太多语句?无论如何,这是我的代码:

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。有谁知道为什么会发生这种情况?谢谢。

最佳答案

完成后,您应该关闭语句和连接,否则资源池可能会耗尽或连接可能会超时。我建议从某些 JDBC 池获取新连接。几年前我曾经在servlet环境中使用proxool。如果你使用J2EE,那么应用服务器会为你做这件事,但你必须使用DataSource。

关于java - java连接MySQL数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20312832/

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