1

I'm dealing with this a few days, and cannot connect to a simple mysql database on localhost.

require "mysql"

@db_host = "localhost"
@db_user = "myrubyapp"
@db_pass = "1234"
@db_name = "myrubyapp"

mysql = Mysql.new(:host => @db_host, :username => @db_user, :password => @db_pass, :database => @db_name)

The output I got is an error: can't convert Hash into String (TypeError) where Mysql.new is.

The second one, I tried to change the gem to mysql2

require "mysql2"

@db_host = "localhost"
@db_user = "myrubyapp"
@db_pass = "1234"
@db_name = "myrubyapp"

mysql = Mysql2.new(:host => @db_host, :username => @db_user, :password => @db_pass, :database => @db_name)

The output is an error too, but is different from the first: undefined method "new" for Mysql2:Module (NoMethodError).

Guys I'm sorry that I have to ask this kind of questions, but I'm really really confused, I have an experience of programming more than 3 years in JavaSE and EE, I am ashamed cause I can't deal with that. Please point me into right direction and don't judge me harshly. I am new to Ruby.

3 Answers 3

3

Try

mysql = Mysql2::Client.new(:host => @db_host, :username => @db_user, :password => @db_pass, :database => @db_name)
Sign up to request clarification or add additional context in comments.

2 Comments

Can't connect to MySQL server on "localhost" (10061) (Mysql2::Error) I tried to put instead of localhost - 127.0.0.1 and it connects, but why?
Maybe because localhost is not getting resolved to 127.0.0.1 or you have a firewall whose ports have been opened only for 127.0.0.1. What OS are you using? If Linux or OSX variants, do you see "127.0.0.1 localhost" or "127.0.0.1 localhost.localdomain localhost" in the /etc/hosts file?
2

correct syntax is:

client = Mysql2::Client.new(:host => "localhost", :username => "root")

see mysql2 on github for more examples

I recomment you to take a look at Sequel as raw mysql2 lib provide a very limited functionality and Sequel can do a lot.

1 Comment

Thanks for the link, and for advice, I'll try as an alternative :)
1

Never used the gem mysql, but have you tried to remove the hash :host => etc and pass directly a list of parameters?
Something like con = Mysql.new db_host, db_user, db_pass, db_name
http://zetcode.com/db/mysqlrubytutorial/ for a tutorial

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.