Thursday, September 01, 2011

Ruby on Rails - Connecting to MySQL on different port.

Hi,

If you are receiving the error "Unknown MySQL server host" because your MySQL is running on non-default port.

con = Mysql.real_connect('127.0.0.1:3308', 'my_user', 'my_password', 'db1')
Mysql::Error: Unknown MySQL server host '127.0.0.1:3308' (11004)
from (irb):14:in `new'
from (irb):14
from C:/Ruby192/bin/irb:12:in `
'


Here, you can't pass the port number with the hostname (as done for several other platforms host:port). You have to pass it as a separate parameter. Took me 20 minutes to figure this out.

con = Mysql.real_connect('127.0.0.1', 'my_user', 'my_password', 'db1', 3308)

All the search results which I got, explained to modify database.yml file which is not there in my case.

Here is a simple script which I used to verify MySQL connectivity in Ruby using Apache server.

#!/Ruby192/bin/ruby
puts "Content-type: text/html"
puts ""
puts "<html>"
puts "<body>

require 'mysql'
con = Mysql.real_connect('localhost', 'my_user', 'my_password', 'db1', 3308)
rs = con.query('select * from member')
rs.each_hash { |h| puts h['Name']}
con.close

puts "</body>
puts "</html>"

Hope this helps !!!

~ Sawan Gupta