跳到主要内容

使用 Ruby 连接数据库

本章节让我们学习如何用 Ruby 来连接数据库,最常用的数据库是 Mysql,因此我们用 Mysql 来做为本章节的例子。

在安装好Ruby的环境的基础上,我们需要安装 Ruby 连接 Mysql 的驱动 mysql2

1. 安装

1.1 安装方式

在这里,我们通过安装 mysql2 的 Gem 来实现。

gem install mysql2

1.2 配置选项

  • --with-mysql-dir[=/path/to/mysqldir]:指定安装 Mysql 的目录,mysql2 的 gem 将不使用mysql_config二进制文件,而是查看mysqldir/lib和`mysqldir/include作为库和头文件。该选项不可以和–with-mysql-config共同使用。
  • --with-mysql-config[=/path/to/mysql_config]:指定Mysql副本提供的二进制文件mysql_config的路径,mysql2 将询问此二进制文件有关编译器和连接器的参数信息。该选项和--with-mysql-dir不可共同使用。

2. 使用

2.1 连接数据库

比如我们现在 Mysql 的用户名是 root,无密码。需要连接本地数据库。

实例:

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

# ---- 输出结果 ----
#<Mysql2::Client:0x00007f8ae50200b8 @read\_timeout=nil, @query\_options={:as=>:hash, :async=>false, :cast\_booleans=>false, :symbolize\_keys=>false, :database\_timezone=>:local, :application\_timezone=>nil, :cache\_rows=>true, :connect\_flags=>2148540933, :cast=>true, :default\_file=>nil, :default\_group=>nil, :host=>"localhost", :username=>"root"}>

解释:

连接上数据库返回 mysql2 客户端实例。

2.2 操作数据库

执行数据库的一系列操作我们需要使用query实例方法。

创建test_db数据库。

client.query("create database if not exists test\_db character set UTF8mb4 collate utf8mb4\_bin;")

创建一个 students 表,里面有一个姓名、年龄字段。

client.query(%{
create table if not exists test\_db.students(
id INT UNSIGNED NOT NULL AUTO\_INCREMENT,
name VARCHAR(255),
age INT UNSIGNED,
PRIMARY KEY ( id )
);
})

students表中插入一条数据:小明,10岁。

client.query("insert into test\_db.students (name, age) values ('小明', 10);")

students表中小明的年龄更改为11岁。

client.query("update test\_db.students set age = 11 where name = '小明';")

查看students的所有数据,需要对结果进行迭代。

results = client.query("select \* from test\_db.students;")
results.each do |result|
p result
end

# ---- 输出结果 ----
{"id"=>1, "name"=>"小明", "age"=>11}

删除name等于小明的这一条数据。

client.query("delete from test\_db.students where name = '小明';")

2.3 更多的链接选项

您可以在Mysql2::Client.new(...)中设置以下连接选项:

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,
:connect\_attrs = {:program\_name => $PROGRAM\_NAME, ...},
:reconnect = true/false,
:local\_infile = true/false,
:secure\_auth = true/false,
:ssl\_mode = :disabled / :preferred / :required / :verify\_ca / :verify\_identity,
:default\_file = '/path/to/my.cfg',
:default\_group = 'my.cfg section',
:default\_auth = 'authentication\_windows\_client'
:init\_command => sql
)

了解更多请去mysql2官网中查看。

3. 小结

本章节我们学习了连接 Mysql 的一个 Gem:mysql2,学习了如何使用它来建立 Ruby 与 Mysql 的连接。学习了使用 mysql2 来进行简单的增删改查(CRUD)操作,并了解了一些常见的配置项。