11

I have written a Java Program and the program connects to a database on my server, to find records, write records, update and delete. for some reason finding records works, but most of the time when i try to save or write a record it gives an error message saying:

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

The last packet successfully received from the server was 9,787 milliseconds ago.       The last packet sent successfully to the server was 8,183 milliseconds ago.

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:2552)
at com.mysql.jdbc.MysqlIO.reuseAndReadPacket(MysqlIO.java:3002)
... 46 more

Can anyone explain why this is happening? Usuually this gives me the error message when trying to add a record, after i had the software running for more than about half a minute. seems to loose connection or something. when i run the program and quickly write a new record, it works

DennisLi
  • 3,915
  • 6
  • 30
  • 66
Pita
  • 498
  • 5
  • 11
  • 21

3 Answers3

4

I was having the same sort of issue. I referred many post and comments but the thing worked for me was changing some parameters of the my.cnf file. Hope it will help you also ....

Set following parameters in my.cnf [mysqld] section

interactive_timeout=180 # "No.of sec. a server waits for activity on interactive connection before closing it"

wait_timeout=180 # "No. of sec. a server waits for an activity on a connection before closing it"

max_connect_errors=9999 # "More than this number of interrupted connections from a host this host will be blocked from further connections"

skip-name-resolve # "Don't resolved host names. All host names are IP's"
Stephan
  • 41,764
  • 65
  • 238
  • 329
jidnesh
  • 41
  • 2
2

Sometimes this problem comes due to size of system RAM.May be you are inserting the data using buffer through RAM. To get out of this problem.

  1. Set the Auto commit disable before inserting the data.
  2. insert some amount of data appropriate to your System RAM (not the whole).
  3. Commit the query.
  4. Do the steps 2 and 3 again until the whole insertion will not be done.

You can understand this by the following code.

public static void main(string args[]) 
{
  Connection con = null;
  Statement stm = null;
  int i;
  float ratio;
  ratio=1.0f;
  try
  {
    Class.forName("com.mysql.jdbc.Driver");
    // Connecting to the database
    con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/demo",
                                      "ashish", "impetus");
    File f = new File("filler"); // taking the random text data from the file
                                 // filler.txt and inserting that string
                                 // in filler field of the relations
    RandomAccessFile r = new RandomAccessFile(f,"r");
    Random randomGenerator = new Random();
    String strLine=new String();
    int r1,flag=0;
    stm = con.createStatement();
    con.setAutoCommit(false) ;

    int k=0;
    i=0;                

    long sum2=0;
    while(k%50000==0)
    {
      final long start = currentTimeMillis();
      final StringBuilder builder =
        new StringBuilder("INSERT INTO accounts 
                           (aid, bid,abalance,filler) VALUES ");
      while(i!=naccounts*ratio*scale )
        {
        int j=i+1;
        for(int l=0;l<40;l++)
        {
          strLine+=((char)r.read());
          r.skipBytes(0);
        }
        r1=randomGenerator.nextInt(1500);
        if(strLine.equals(""))
        {
          flag=1;
        }
        if(flag!=1)
        {   
          strLine=strLine.replaceAll("\\s","");
          strLine=strLine.replaceAll("\\t","");
        }                   
        flag=0;
        if (i%50000!=0) 
        {
          builder.append(",");
        }
        builder.append(format("(%s, %s, %s, '%s')", j, 
                       i/naccounts+1, 0, strLine));
        strLine="";
        r.seek(r1);
        i++;
        if(i%50000==0||i>=naccounts*ratio*scale)
        {   
          final String query = builder.toString();
          final PreparedStatement statement1 = con.prepareStatement(query);
          statement1.execute();
          con.commit();
          final long stop= currentTimeMillis();
          sum2=sum2+(stop-start);
          statement1.close();
        }
        if(i%50000==0||i>=naccounts*ratio*scale)
        {
          break;
        }
      }
      k=k+50000;
      if(k>naccounts*ratio*scale)
      {
        break;
      }
    }
    System.out.println(i+" rows inserted accounts table ");
    System.out.println("time taken = "+sum2+" milliseconds");
  }
  catch (SQLException e)
  {
    System.out.println("Connection Failed! Check output console");
    e.printStackTrace();
    return;
  }
  catch (Exception e) 
  {
    e.printStackTrace();
  }
}
Jack
  • 10,943
  • 13
  • 50
  • 65
ashish
  • 171
  • 1
  • 7
0

Did you follow/read this tutorial :

Connectivity with MYSQL

You have a part for your exception which can be useful for you.

I will quote something about your specific exception, just try that :

If you get a SQLException: Connection refused or Connection timed out or a MySQL specific CommunicationsException: Communications link failure, then it means that the DB isn't reachable at all. This can have one or more of the following causes:

IP address or hostname in JDBC URL is wrong. Hostname in JDBC URL is not recognized by local DNS server. Port number is missing or wrong in JDBC URL. DB server is down. DB server doesn't accept TCP/IP connections. DB server has run out of connections. Something in between Java and DB is blocking connections, e.g. a firewall or proxy.

To solve the one or the other, follow the following advices:

Verify and test them with ping. Refresh DNS or use IP address in JDBC URL instead. Verify it based on my.cnf of MySQL DB. Start the DB. Verify if mysqld is started without the --skip-networking option. Restart the DB and fix your code accordingly that it closes connections in finally. Disable firewall and/or configure firewall/proxy to allow/forward the port.

Community
  • 1
  • 1
ChapMic
  • 26,954
  • 1
  • 21
  • 20
  • i followed it, but i done everything right according to your url. I think its the time out session, which is preventing me from doing things to my db. is there any way, to prevent the time out session? I have read something about maxWait indefinate, but cant find anythng specific to how to declare that, so that the system would wait no matter how long it takes until response is received. – Pita Mar 13 '12 at 15:58