Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql2: close client connection

I am using Mysql2 to query a database on ruby. I initialize the connection by:

client = Mysql2::Client.new(:host => "localhost", :database => 'mydb', :username => "root")

Once the query is done successfully, how can I close the client connection? If I do not close it, I soon reach the maximum number of possible open connections.

Solution

Thanks to @joonty:

client.close

like image 360
Marco Avatar asked Aug 12 '13 06:08

Marco


1 Answers

Use client.close. From the docs:

Mysql2::Client#close

Immediately disconnect from the server, normally the garbage collector will disconnect automatically when a connection is no longer needed. Explicitly closing this will free up server resources sooner than waiting for the garbage collector.

Have you got multiple long-running processes that only use the mysql connection for a short time? That should be the only case where this is an issue. If your processes are ending then the connection will be closed as part of garbage collection, so your issue lies elsewhere.

like image 100
Jon Cairns Avatar answered Oct 04 '22 22:10

Jon Cairns