active record losing connection, in non-Rails script

This isn't a Rails program, but since ActiveRecord is a part of Rails I thought it would be fitting to post here. Anyway, sorry if anyone is bothered by that.

My problem is that I occasionally get this error: "Mysql::Error: MySQL server has gone away" with an ActiveRecord::StatementInvalid exception. I understand that what I need to do is make sure the connection is active before accessing the database, but I'm not sure the best way to do that.

Here is my code at a glance:

# some requires and some constants ActiveRecord::Base.establish_connection(dbconfig) # some code # start of a loop   # some code   Entry.create(:name => name_variable, :info => info_variable) # end

It's a very long-running script. Sometimes the loop takes 10 minutes, sometimes it takes several hours.

I've come up with two possible solutions. One is to recreate the connection before every database activity with "ActiveRecord::Base.verify_active_connections!" so my code would look like this:

  # some code   ActiveRecord::Base.verify_active_connections!   Entry.create(:name => name_variable, :info => info_variable) # end

The other solution is to rescue the ActiveRecord::StatementInvalid which I think would look something like this:

  # some code   begin     Entry.create(:name => name_variable, :info => info_variable)   rescue ActiveRecord::StatementInvalid     ActiveRecord::ConnectionAdapters::AbstractAdapter.reconnect!     Entry.create(:name => name_variable, :info => info_variable)   end # end

But I have no idea if I'm doing that reconnect correctly. Any help on whether or not any one of these is correct, is either one better, or is there a better way than either of these?

In the past we did the latter, but instead of rescuing it just did it prior to any database statement after something that we knew was going to take awhile. These were mostly data migration scripts so we'd do a lot of munging, then ensure we were connected then stuff them all in.

-philip