使用ruby将MAMP作为本地服务器访问SQL

时间:2017-05-02 09:58:51

标签: mysql ruby

我正在尝试使用ruby作为前端工具来访问我的SQL数据库,但是我遇到了一些错误。首先,我使用MAMP作为在我的计算机上设置本地SQL服务器的工具,我使用MYSQL工作台访问MAMP没有问题,我已经设置了几个数据库。但是,当我尝试使用此代码通过Ruby访问数据库时:

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

我在终端中收到此错误:

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'     来自sql.rb:4:在`'

我在想我必须改变mysql.sock的位置,但我不完全确定如何做到这一点。有人可以帮忙吗?

编辑:解决方案是:

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

1 个答案:

答案 0 :(得分:0)

根据mysql gem http://www.rubydoc.info/gems/mysql/2.9.1/Mysql#new-class_method的文档(不要混淆mysql2 gem)参数建立与mysql服务器的连接,朝这个方向前进:

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

所以你需要在端口声明后添加一个到mysql进程的socket的路径。在你的情况下,它会是这样的:

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