mohnstrudel
mohnstrudel

Reputation: 649

Connect to mysql with Ruby but without Rails

I am using my old script, which used to work just fine, but now I'm receiving following error:

Error while connecting to the database.
Can't connect to MySQL server on 'some.remote.host.com' (65)

I can't figure out what the real error is, my connect data is surely correct, because I can login to PhPMyadmin with the given username and password.

Here is my code:

# encoding: UTF-8

require 'mysql2'
require 'csv'

def initialize_data
  puts "Initializing database, username, password and host..."
  @database = "database_name"
  @username = "database_user"
  @password = "my_secret_password"
  @host = "remote.host.com"
end

def connect
  puts "Trying to connect to the database."
  begin 
    @client = Mysql2::Client.new(host: @host, username: @username, password: @password, database: @database)
  rescue => e
    puts "Error while connecting to the database."
    puts e.message
  end
end

I wasn't able to find any info on this 65 error. Rescuing with e.message does not help at all.

Can someone point me at least in what direction to dig? I'm struggling with this simple script second day in a row now. Is there any way to receive more detailed error messages? Like Rails' error.full_messages.each

Upvotes: 1

Views: 481

Answers (1)

Kathryn
Kathryn

Reputation: 1597

You can look up MySQL error codes with perror:

$ perror 65
OS error code  65:  No route to host

That might mean the MySQL server is on a network you can't currently reach. If so, you haven't reached the point where the username and password matters. An easy way to test if the problem is with your code or with accessing the database is to use the command-line tool. If you can't reach the database from the command line you are running Ruby from, the problem isn't your code.

Another test would be to run MySQL locally. (Or run your script on the same machine as the MySQL database, if possible.) If the script works as expected, check to see if there's been a recent change in network or database configuration.

Upvotes: 1

Related Questions