Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql2 Error MySQL server has gone away

I am getting this error occasionally. I have read some solutions in stackoverflow but they were about rails 2 or mysql. Any help will be appreciated.

ActiveRecord::StatementInvalid (Mysql2::Error: MySQL server has gone away
like image 605
ziCk Avatar asked Jul 24 '11 13:07

ziCk


People also ask

How do I fix the error MySQL server has gone away?

To fix, you can increase the maximal packet size limit max_allowed_packet in my. cnf file, eg. set max_allowed_packet = 128M , then restart your MySQL server: sudo /etc/init. d/mysql restart.

What does MySQL server has gone away mean?

The MySQL server has gone away error, which means that the MySQL server (mysqld) timed out and closed the connection. By default, MySQL will close connections after eight hours (28800 seconds) if nothing happens.

Can't connect to MySQL server timed out?

A Connection Timed Out error occurs when the database's firewall won't allow you to connect to the database from your local machine or resource. If you are getting this error, check that you have added the machine or resource you are connecting from to the database's list of trusted sources.

What is max allowed packet size in MySQL?

The largest possible packet that can be transmitted to or from a MySQL 8.0 server or client is 1GB. When a MySQL client or the mysqld server receives a packet bigger than max_allowed_packet bytes, it issues an ER_NET_PACKET_TOO_LARGE error and closes the connection.


2 Answers

I got this error while trying to import a large file through seeds.rb with rake db:seed by calling one statement:

ActiveRecord::Base.connection.execute(IO.read("path/to/file.sql"))

And I kept on getting ActiveRecord::StatementInvalid (Mysql2::Error: MySQL server has gone away...


SOLUTION

I resolved this by a combination of two things:

  1. Add reconnect: true to the database specification in database.yml
  2. Read the SQL file and execute the statement individually, as such:

    f = File.new('path/to/file.sql')
    
    while statements = f.gets("") do
      ActiveRecord::Base.connection.execute(statements)
    end  
    

I had to modify to remove some comments from my SQL file -- they made ActiveRecord throw errors for some reason, but that resolved my problem.

like image 73
Yuval Karmi Avatar answered Nov 14 '22 06:11

Yuval Karmi


There are numerous causes for the error. See below page for possible causes. Perhaps your packet size is set too small.

http://dev.mysql.com/doc/refman/5.0/en/gone-away.html

like image 8
Ray Fix Avatar answered Nov 14 '22 08:11

Ray Fix