Mysql2 Error MySQL server has gone away

↘锁芯ラ 提交于 2019-11-29 09:30:14

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

Yuval Karmi

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.

I experience exactly same issue when I run "rake db:reset" command on my development environment. But I never see this error message when I run "rake db:migrate:reset && rake db:seed".

Though it is very strange, but this may throw some lights on this issue. I am glad if my post leads to a solution somehow.

Maybe the server you are hosted on is overloaded and in some cases the MySQL server can not execute a query. Ask your hosting provider about performance monitoring tools, or tell him about this problem directly. This error message should be enough for them to give you an answer.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!