简体   繁体   中英

Accessing SQL using ruby with MAMP as a local server

I am trying to access my SQL databases using ruby as a front end tool, however I'm running into a couple of errors along the way. Firstly, I'm using MAMP as a tool to set up a local SQL server on my computer, and I have no problem accessing MAMP using MYSQL workbench and I've set up a couple of databases. However, when I'm trying to access the database via Ruby using this code:

require 'mysql'

begin
  connection = Mysql.new 'localhost', 'root', 'root', nil, 8889
  connection.list_dbs.each do |db|
    puts db
  end

rescue Mysql::Error => e
  puts e.errno
  puts e.error

ensure
  connection.close if connection
end

I get this errors in terminal:

Vetles-MacBook-Pro:ruby Vetle$ ruby sql.rb /Library/Ruby/Gems/2.0.0/gems/ruby-mysql-2.9.14/lib/mysql/protocol.rb:150:in initialize': No such file or directory - "/tmp/mysql.sock" (Errno::ENOENT) from /Library/Ruby/Gems/2.0.0/gems/ruby-mysql-2.9.14/lib/mysql/protocol.rb:150:in new' from /Library/Ruby/Gems/2.0.0/gems/ruby-mysql-2.9.14/lib/mysql/protocol.rb:150:in block in initialize' from /System/Library/Frameworks/Ruby.framework/Versions/2.0/usr/lib/ruby/2.0.0/timeout.rb:52:in timeout' from /Library/Ruby/Gems/2.0.0/gems/ruby-mysql-2.9.14/lib/mysql/protocol.rb:147:in initialize' from /Library/Ruby/Gems/2.0.0/gems/ruby-mysql-2.9.14/lib/mysql.rb:115:in new' from /Library/Ruby/Gems/2.0.0/gems/ruby-mysql-2.9.14/lib/mysql.rb:115:in connect' from /Library/Ruby/Gems/2.0.0/gems/ruby-mysql-2.9.14/lib/mysql.rb:50:in new' from sql.rb:4:in `'

I am thinking I have to change the location of the mysql.sock, but I am not completely sure how to do this. Can anyone help?

EDIT: Solution was:

require 'mysql'

begin
  connection = Mysql.new 'localhost', 'root', 'root', nil, 8889, '/Applications/MAMP/tmp/mysql/mysql.sock'
  connection.list_dbs.each do |db|
    puts db
  end

rescue Mysql::Error => e
  puts e.errno
  puts e.error

ensure
  connection.close if connection
end

Based on documentation of mysql gem http://www.rubydoc.info/gems/mysql/2.9.1/Mysql#new-class_method (do not mess with mysql2 gem) parameters to establish connection to mysql server go in this direction:

host, user, passwd, db, port, sock, flag

So you need to add a path to socket of mysql process after port declaration. And in your case it would be like this:

Mysql.new 'localhost', 'root', 'root', nil, 8889, '/<path to sock file>/mysql.sock'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM