1

正如我在标题中所说,我与 mysql 服务器的 JDBC 连接在大约 10-20 分钟不活动后失败。我使用以下代码连接到数据库:

import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.*;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;

public class MyDB
{
    public Connection connect = null;
    public Statement statement = null;
    public PreparedStatement preparedStatement = null;
    public ResultSet resultSet = null;

    public void readDatabase() throws Exception
    {
        JSch jsch = new JSch();
        String host = "ssh.binero.se";
        String user = "username";
        Session session = jsch.getSession(user, host, 22);
        int lport = 1234;
        String rhost = "Ip_to_host";
        int rport = 3306;
        UserInfo ui = new MyUserInfo();
        session.setUserInfo(ui);
        session.connect();

        int assigned_port = session.setPortForwardingL(lport, rhost, rport);
        System.out.println("localhost:" + assigned_port + " -> " + rhost + ":" + rport);
        Class.forName("com.mysql.jdbc.Driver");
        connect = DriverManager
            .getConnection("jdbc:mysql://localhost:1234/database?
            user=user&password=pass&connectTimeout=28800000");

这工作正常,但在大约 10-20 分钟不活动后,当我尝试使用数据库连接时收到以下错误消息:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet successfully received from the server was 6 810 583 milliseconds ago.
The last packet sent successfully to the server was 6 810 800 milliseconds ago.

...

Caused by: java.net.SocketException: Software caused connection abort: socket write error

我知道我可以通过在每次查询后断开与数据库的连接来解决这个问题,但我不希望这样做。另外,由于我在一段时间后与数据库断开连接,我以为我被超时了。但是,当我更改它们时,我没有发现任何有帮助的变量。

4

1 回答 1

-2
       Class.forName("com.mysql.jdbc.Driver");
       con = DriverManager.getConnection("jdbc:mysql://localhost:3306/Table_Name","root","");

试试这个,我从来没有超时!祝你好运...!

于 2012-07-11T10:18:13.277 回答