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
解决方案
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.