Mysql2 Error MySQL server has gone away

无人久伴 提交于 2019-11-28 02:52:31

问题


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

回答1:


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




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/6807012/mysql2-error-mysql-server-has-gone-away

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