TCP connection to local MySQL with Ruby

Here’s a small detail that took me a while to discover. Maybe it helps you, or at least it’ll probably help me in the future when I need to do this again…

I was working on a ruby script which made some calls to MySQL. Among other things, the script takes an argument with the hostname of the database which it later uses to open the connection. The implementation is a bit too smart for its own good though.. if the hostname is “localhost” it won’t do a TCP connection. I needed to force it to do a TCP connection even if it was localhost. I couldn’t find it clearly documented anywhere, but turns out there is a way. You need to set the OPT_PROTOCOL option to 1:

h = Mysql.init
h.options(Mysql::OPT_PROTOCOL, 1) # 1=TCP, force TCP connection
connection = h.real_connect(dbhost, $MYSQL_UID, $MYSQL_PWD)

That’ll do it.

As to why I needed this? The MySQL server was actually on a different server but I had set up an ssh tunnel to it mapped to localhost:3306. So, the ruby MySQL library assumption that “localhost” connection must be to a local process was not true in this case.