如何从java应用程序创建mysql持久连接?

时间:2011-06-14 19:06:48

标签: java mysql database

您好我正在编写一个需要与mysql数据库建立持久连接的java应用程序。我无权访问数据库服务器,因此无法更改数据库服务器上的任何内容,因此无法关闭连接。

我收到以下错误:

Exception in thread "main" com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet successfully received from the server was 368,140 milliseconds ago.  The last packet sent successfully to the server was 366,869 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:409)
    at com.mysql.jdbc.SQLError.createCommunicationsException(SQLError.java:1118)
    at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3055)
    at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2941)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3489)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1959)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2113)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2568)
    at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2113)
    at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:2275)
    at SearchAndUpdate.recursiveUpdate(SearchAndUpdate.java:101)
    at SearchAndUpdate.recursiveUpdate(SearchAndUpdate.java:110)
    at SearchAndUpdate.recursiveUpdate(SearchAndUpdate.java:110)
    at SearchAndUpdate.recursiveUpdate(SearchAndUpdate.java:110)
    at SearchAndUpdate.recursiveUpdate(SearchAndUpdate.java:110)
    at SearchAndUpdate.recursiveUpdate(SearchAndUpdate.java:110)
    at SearchAndUpdate.recursiveUpdate(SearchAndUpdate.java:110)
    at SearchAndUpdate.recursiveUpdate(SearchAndUpdate.java:110)
    at SearchAndUpdate.recursiveTraversal(SearchAndUpdate.java:55)
    at SearchAndUpdate.main(SearchAndUpdate.java:40)
Caused by: java.net.SocketException: Connection reset
    at java.net.SocketInputStream.read(Unknown Source)
    at com.mysql.jdbc.util.ReadAheadInputStream.fill(ReadAheadInputStream.java:114)
    at com.mysql.jdbc.util.ReadAheadInputStream.readFromUnderlyingStreamIfNecessary(ReadAheadInputStream.java:161)
    at com.mysql.jdbc.util.ReadAheadInputStream.read(ReadAheadInputStream.java:189)
    at com.mysql.jdbc.MysqlIO.readFully(MysqlIO.java:2499)
    at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:2952)
    ... 17 more

我假设此消息告诉我连接正在自动关闭。我不确定是否创建了持久连接......如果有人在java代码中给我一些指令,我将非常感激。非常感谢提前。

以下是我创建连接的代码:

import java.sql.*;

   public class Connect
   {
       public static void main (String[] args)
       {
           Connection conn = null;

           try
           {
               String userName = "sdfasdfsf";
               String password = "asdfasdfsd";
               String url = "jdbc:mysql://nameOfcomputer:3306/databasename";
               Class.forName ("com.mysql.jdbc.Driver").newInstance();
               conn = DriverManager.getConnection (url, userName, password);
               System.out.println ("Database connection established");
           }
           catch (Exception e)
           {
               System.err.println ("Cannot connect to database server");
               System.out.println(e.getMessage());
           }

       }
   }

我刚刚在网上找到了以下示例:

http://www.java2s.com/Tutorial/Java/0340__Database/KeeptheConnectionAliveforMySQL.htm

这会是持久连接的一个例子吗?

我的代码通过使用我发布的相同代码来获取连接,并运行超过4个小时更新mysql中的表。应用程序基本上对目录进行递归搜索,查找所有文件并获取文件的信息,然后将信息输入数据库。该目录是搜索包含更多感谢100,000文件。连接有时会关闭,因为有时程序需要一段时间 递归查找文件,以下是我的代码:

public class Search{

    public static void main(String[] args) throws SQLException 
    {
        File fileObject = new File("scanLocation");
        Connection conn = getConnection();

        update(fileObject, conn);           
        conn.close();
    }

    public static void update(File fileObject, Connection conn)throws SQLException 
    {   
        if (fileObject.isDirectory()) 
        {
            File allFiles[] = fileObject.listFiles();
            if (allFiles != null) 
            {
                for (File aFile : allFiles) 
                {               
                    if (aFile.isFile()) 
                    {
                        String filename=aFile.aFile.getName();
                        String query = "INSERT INTO table(" 
                                       + "File_Name" +")"
                                       +  " Values (?)";
                        try 
                        {   PreparedStatement psmt=conn.prepareStatement(query);
                                psmt.setString(1, fileName);
psmt.executeUpdate();

                        } 
                        catch (SQLException e) 
                        {
                            System.out.println("SQLExceptoin - " + e.getMessage());
                            System.out.println("SQLState: " + e.getSQLState());
                            System.out.println("VendorError: " + e.getErrorCode());
                            e.printStackTrace();
                        }

                    }
                    else
                    {
                        recursiveUpdate(aFile, conn);
                    }
                }
            }
        }
    }

    public static Connection getConnection()
    {
        String DATABASE_USER = "user";
        String DATABASE_PASSWORD = "password";
        String MYSQL_AUTO_RECONNECT = "autoReconnect";
        String MYSQL_MAX_RECONNECTS = "maxReconnects";

        Connection conn = null;
        try 
        {
            String userName = "username";
            String password = "password";
            String url = "jdbc:mysql://compName:3306/database";

            Class.forName("com.mysql.jdbc.Driver").newInstance();
            conn = DriverManager.getConnection(url, userName, password);

            java.util.Properties connProperties = new java.util.Properties();
            connProperties.put(DATABASE_USER, userName);
            connProperties.put(DATABASE_PASSWORD, password);

            connProperties.put(MYSQL_AUTO_RECONNECT, "true");

            connProperties.put(MYSQL_MAX_RECONNECTS, "4");
            return DriverManager.getConnection(url, connProperties);
        } 
        catch (Exception e) 
        {
            System.err.println("Cannot connect to database server");
            System.out.println(e.getMessage());
            e.printStackTrace();
        }
        return conn;
    }


}

程序有时会完成,有时数据库服务器强制关闭连接?由于我没有对数据库服务器的任何访问权限,我该怎么办才能使数据库服务器不关闭连接?

非常感谢

1 个答案:

答案 0 :(得分:0)

好吧,如果您无法控制服务器何时关闭连接,那么您将不得不打开一个新连接。在这种情况下,您不能拥有真正的持久连接(尽管您可以为其创建一个外观) - 您必须检测到一个已关闭并重新打开一个连接。