使用mysql2 Ruby gem确定mysql2服务器版本

Abd*_*bdo 4 ruby ruby-on-rails mysql2

我正在使用Railsmysql2宝石。有没有一种方法可以通过运行命令来获取mysqld服务器版本:

$ mysqld --version
mysqld  Ver 5.5.29 for osx10.8 on i386 (Source distribution)
Run Code Online (Sandbox Code Playgroud)

我不希望执行shell命令,因为数据库服务器可能正在另一台服务器上运行。

Max*_*ams 5

您可以通过ActiveRecord :: Base.connection在rails中获取版本信息。我在这里的Rails控制台中进行操作。我使用的是Rails的旧版本(2.2),因此语法可能与您的不同。

irb(main):190:0> ActiveRecord::Base.connection.select_rows("SHOW VARIABLES LIKE '%version%'")
=> [["innodb_version", "5.5.34"], ["protocol_version", "10"], ["slave_type_conversions", ""], ["version", "5.5.34-0ubuntu0.12.04.1"], ["version_comment", "(Ubuntu)"], ["version_compile_machine", "x86_64"], ["version_compile_os", "debian-linux-gnu"]]
Run Code Online (Sandbox Code Playgroud)

一旦掌握了这些,就可以提取所需的信息,例如:

version = ActiveRecord::Base.connection.select_rows("SHOW VARIABLES LIKE '%version%'").detect{|field,val| field == "version"}.last
=> "5.5.34-0ubuntu0.12.04.1"
Run Code Online (Sandbox Code Playgroud)