Ruby 连接 MySQL(mysql2 驱动)
介绍 Ruby 生态主流高性能 MySQL 客户端库 mysql2 的安装与编译配置、Client 连接参数、SQL 转义与预处理、结果集计数与哈希行遍历。
学完这一章,你能够
- 介绍 Ruby 生态主流高性能 MySQL 客户端库 mysql2 的安装与编译配置、Client 连接参数、SQL 转义与预处理、结果集计数与哈希行遍历。
mysql2 定位、安装与建立连接
相较早期的 `ruby-dbi` 与 `mysql` 扩展,`mysql2` 是目前 Ruby 生态(含 Rails ActiveRecord)最推荐的高性能 MySQL 原生 C 扩展驱动。安装只需执行 `gem install mysql2`;若系统 `mysql_config` 不在默认搜索路径中,可附加编译选项 `-- --with-mysql-config=/path/to/mysql_config`。建立连接时向 `Mysql2::Client.new` 传入哈希参数(如 `:host => '127.0.0.1'`、`:username`、`:password`、`:database`、`:encoding => 'utf8mb4'`),现代项目建议优先使用 `utf8mb4` 编码以完整支持四字节 Unicode 字符。
执行查询、字符转义、结果集遍历与连接选项
调用 `results = client.query(sql)` 执行 SQL 并返回 `Mysql2::Result` 对象。若动态拼接字符串条件,必须先调用 `client.escape(str)` 转义单引号、双引号与 NUL 字节,或在 `mysql2` 0.4+ 中直接使用 `client.prepare(sql)` 预处理语句绑定参数以杜绝 SQL 注入。可通过 `results.count` 获取命中行数,调用 `results.each { |row| ... }` 按哈希方式读取每一行(键为列名字符串,整型列自动转为 Ruby `Integer`,不存在的键返回 `nil`;如执行 `SELECT VERSION()` 输出 `{"VERSION()"=>"5.6.21"}`)。
`Mysql2::Client.new` 支持精细化连接配置,包括 `:host`、`:username`、`:password`、`:port`、`:database`、`:socket`、`:flags`(如事务与多语句标志)、`:encoding`、`:read_timeout`、`:write_timeout`、`:connect_timeout`、`:reconnect`、`:local_infile`(出于安全建议关闭)、`:secure_auth`、`:default_file`、`:default_group` 与 `:init_command`。实际书写时应使用标准的 Ruby 哈希键值对语法(`:key => value` 或 `key: value`),而非伪代码中的赋值等号 `=`。
离线以内存 SQLite 模拟 mysql2 连接选项、字符转义与哈希结果集
"""Offline Ruby 3.x semantic verification lab for Chapter 34 (mysql-mysql2)."""
import json
import sqlite3
VERSION = "CPython 3.12.14 offline Ruby 3.x semantic verifier (SQLite in-memory mysql2 model, MRI ruby absent)"
def mysql2_escape(val: str) -> str:
repl = {"\\": "\\\\", "'": "\\'", '"': '\\"', "\x00": "\\0", "\n": "\\n", "\r": "\\r", "\x1a": "\\Z"}
return "".join(repl.get(ch, ch) for ch in val)
def case_mysql2_options_and_dsn_config():
opts = {
"host": "127.0.0.1",
"username": "root",
"port": 3306,
"database": "test",
"encoding": "utf8mb4",
"read_timeout": 5,
"write_timeout": 5,
"connect_timeout": 3,
"reconnect": False,
"local_infile": False,
"secure_auth": True,
}
expected = {
"host": "127.0.0.1",
"encoding": "utf8mb4",
"timeouts_positive": True,
"local_infile_disabled": True,
}
actual = {
"host": opts["host"],
"encoding": opts["encoding"],
"timeouts_positive": opts["read_timeout"] > 0 and opts["write_timeout"] > 0 and opts["connect_timeout"] > 0,
"local_infile_disabled": opts["local_infile"] is False,
}
return {
"name": "mysql2_options_and_dsn_config",
"summary": "核验 Mysql2::Client.new 哈希连接参数(host/database/encoding/超时与安全开关)结构",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_mysql2_escape_and_sql_safety():
raw = "gi'thu\"bbe\x00r's"
escaped = mysql2_escape(raw)
conn = sqlite3.connect(":memory:")
cur = conn.cursor()
cur.execute("CREATE TABLE users (id INT, grp TEXT)")
cur.execute("INSERT INTO users VALUES (1, 'githubbers'), (2, ?)", (raw,))
# Parameterized query prevents SQL injection from raw quotes
matched = cur.execute("SELECT id FROM users WHERE grp = ?", (raw,)).fetchall()
conn.close()
expected = {
"escaped": r"gi\'thu\"bbe\0r\'s",
"contains_raw_nul": False,
"prepared_match_ids": [2],
}
actual = {
"escaped": escaped,
"contains_raw_nul": "\x00" in escaped,
"prepared_match_ids": [r[0] for r in matched],
}
return {
"name": "mysql2_escape_and_sql_safety",
"summary": "核验 client.escape 对单双引号与 NUL 字节的转义及预处理参数化查询防注入语义",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def case_mysql2_hash_rows_and_count():
conn = sqlite3.connect(":memory:")
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute("CREATE TABLE users (id INTEGER, name TEXT, grp TEXT)")
cur.executemany(
"INSERT INTO users VALUES (?, ?, ?)",
[(101, "Alice", "githubbers"), (102, "Bob", "githubbers"), (103, "Cara", "ops")],
)
results = [dict(row) for row in cur.execute("SELECT id, name FROM users WHERE grp = ?", ("githubbers",)).fetchall()]
conn.close()
missing_keys = [r.get("dne") for r in results]
expected = {
"count": 2,
"first_id_type": "int",
"ids": [101, 102],
"missing_column_is_nil": [None, None],
}
actual = {
"count": len(results),
"first_id_type": type(results[0]["id"]).__name__,
"ids": [r["id"] for r in results],
"missing_column_is_nil": missing_keys,
}
return {
"name": "mysql2_hash_rows_and_count",
"summary": "核验 Mysql2::Result#count、按列名返回哈希行以及读取不存在列返回 nil 的行为",
"expected": expected,
"actual": actual,
"passed": actual == expected,
}
def main():
cases = [
case_mysql2_options_and_dsn_config(),
case_mysql2_escape_and_sql_safety(),
case_mysql2_hash_rows_and_count(),
]
print(json.dumps({"version": VERSION, "cases": cases}, ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
- 3 个确定性用例全部通过(不连接宿主机 MySQL),验证连接选项、转义防注入及哈希行读取与 count。
所需环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。
当前源码 SHA256:c6eb547ea380b2bb4ee3cc22abf5d80a831bac966fef34c65dacec34a180672f
本地运行
解压后按 README 说明在对应本地环境运行脚本。
所需环境:Windows x64、CPython 3.12.14 离线 Ruby 3.x 语义验证器(本机未安装 MRI ruby 解释器)。
ZIP SHA256:d03330c9464f0952bfe5d629632f090ad33a81697dc0f8abe9dbb0690c8831b6
常见错误与边界
- 实际端口、文档资源与应用配置都应和测试条件一致。
练习与解答
在 `mysql2` 中迭代 `results.each { |row| ... }` 时,访问查询中未包含的字段 `row["dne"]` 会抛出异常还是返回 `nil`?
展开参考解答
`row` 默认是一个普通 Ruby `Hash`,访问不存在的键会返回 `nil` 而不是抛出异常。