eonil
eonil

Reputation: 85975

How to close MySQL connection & quit program immediately in Ruby?

Here's my program.

require "mysql"

db  =   Mysql.new("127.0.0.1", "root", "some password", "test")
db.close
db  =   nil

When I run this program, it doesn't finishes. I need to send Ctrl+C to stop execution.

How can I make this program close the connection and quit immediately and gracefully? (Ruby 2.0.0)

Update

I discovered new symptom. It hangs instead of quit and seems like running an infinite loop. Because my CPU monitor told me it is using 100% of one core. I am not still sure this is Ruby issue or MySQL library issue or my configuration issue...

Upvotes: 0

Views: 687

Answers (2)

eonil
eonil

Reputation: 85975

I finally figured out workaround. I have installed all brew, rvm, ruby almost 10 times to figure out where the problem is. It was because of bad MySQL connector C library.

I installed the connector with Homebrew,

brew install mysql-connector-c

and used wrapper version of ruby gem.

gem install mysql

Anyway I tried pure-ruby based version and it doesn't hang. works well.

brew remove mysql-connector-c
gem uninstall mysql
gem cleanup all

gem install ruby-mysql

# Now everything working well without hanging at last.

Anyway, mysql-connector-c package and mysql gem works fine on Ubuntu Linux. (I am using OS X) So the core problem was OS X version of C connector installed by brew.

This could be a little bit slower, but it doesn't matter on dev machine, because final distribution will be based on Linux.

Upvotes: 0

awendt
awendt

Reputation: 13663

Your script is fine.

In your specific case, it doesn't quit because the client times out when conecting to the server at the given IP 10.211.55.10. It never even gets to db.close.

I've reproduced this locally. I changed the code to connect to my local MySQL and the script quits immediately.

I can reproduce the same hanging when I manually connect with the client:

$ mysql -u root -p -h 10.211.55.10
Enter password: [masked]
ERROR 2003 (HY000): Can't connect to MySQL server on '10.211.55.10' (60)

The error message appears after timing out. Are the credentials correct? Does the server accept connections?

Upvotes: 1

Related Questions