如何检查mysql连接

时间:2016-08-04 10:49:16

标签: ruby ruby-on-rails-3

我想在执行查询之前检查是否存在与数据库的连接。

但是当我写if mysql_connection ...时,它会在mysql_connection上传递两次:

def mysql_connection
  puts "mysql_connection 1"

  read_config_file
  @connexion = Mysql2::Client.new(:host => @conf['host'], :username => @conf['user'], :password => @conf['password'], :database=> @conf['base'], :port => @conf['port'])
end 

# USER QUERY MYSQL
def mysql_select_user(value)
  puts "select"

  # if mysql_connection then
    p = mysql_connection.query("select #{value} from User")   
    p.each do |f| 
      puts "value : #{f}" 
      mysql_close
    end 
  # else
  # end 
end 

1 个答案:

答案 0 :(得分:0)

使用Mysql2::Client#ping方法(来自文档:http://www.rubydoc.info/gems/mysql2/0.3.13/Mysql2/Client#ping-instance_method