Ruby 连接 Mysql MySql2

前面一章节我们介绍了 Ruby DBI 的使用。这章节我们技术 Ruby 连接 Mysql 更高效的驱动 mysql2,目前也推荐使用这种方式连接 MySql。

安装 mysql2 驱动:

geminstallmysql2

你需要使用 –with-mysql-config 配置 mysql_config 的路径,如: –with-mysql-config=/some/random/path/bin/mysql_config

连接

连接数据库语法如下:

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

更多参数可以查看 http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/MysqlAdapter.html

查询

results=client.query("SELECT*FROMusersWHEREgroup='githubbers'")

特殊字符转义

escaped=client.escape("gi'thu\"bbe\0r's")results=client.query("SELECT*FROMusersWHEREgroup='#{escaped}'")

计算结果集返回的数量:

results.count

迭代结果集:

results.eachdo|row|#row是哈希#键值是数据库字段#值都是对应MySQL中数据putsrow["id"]#row["id"].class==Fixnumifrow["dne"]#不存在则是nilputsrow["dne"]endend

在线示例

#!/usr/bin/ruby-wrequire'mysql2'client=Mysql2::Client.new(:host=>'127.0.0.1',#主机:username=>'root',#用户名:password=>'123456',#密码:database=>'test',#数据库:encoding=>'utf8'#编码)results=client.query("SELECTVERSION()")results.eachdo|row|putsrowend

以上示例运行输出结果为:

{"VERSION()"=>"5.6.21"}

连接选项

Mysql2::Client.new(:host,:username,:password,:port,:database,:socket='/path/to/mysql.sock',:flags=REMEMBER_OPTIONS|LONG_PASSWORD|LONG_FLAG|TRANSACTIONS|PROTOCOL_41|SECURE_CONNECTION|MULTI_STATEMENTS,:encoding='utf8',:read_timeout=seconds,:write_timeout=seconds,:connect_timeout=seconds,:reconnect=true/false,:local_infile=true/false,:secure_auth=true/false,:default_file='/path/to/my.cfg',:default_group='my.cfgsection',:init_command=>sql)

更多内容请参阅:http://www.rubydoc.info/gems/mysql2/0.2.3/frames

编辑于2024-05-20 15:58