一、mysql2 概述
-
mysql2 是一个用于
Node.js
的 MySQL 客户端库 -
mysql2 是 mysql 库的一个改进版本,提供了更好的性能和更多的功能
-
使用 mysql2 之前,需要先安装它
npm install mysql2
二、mysql2 基本操作
数据库准备
- 创建数据库 testdb
CREATE DATABASE testdb;
- 创建数据表 employees
CREATE TABLE IF NOT EXISTS employees (
id INT AUTO_INCREMENT PRIMARY KEY,
firstName VARCHAR(50) NOT NULL,
lastName VARCHAR(50) NOT NULL,
email VARCHAR(100) NOT NULL UNIQUE,
phone VARCHAR(20),
hireDate DATE,
jobTitle VARCHAR(50)
);
- 添加一些测试数据
INSERT INTO employees (firstName, lastName, email, phone, hireDate, jobTitle) VALUES
('John', 'Doe', '[email protected]', '123-456-7890', '2023-01-15', 'Software Engineer'),
('Jane', 'Smith', '[email protected]', '098-765-4321', '2022-07-22', 'Product Manager'),
('Alice', 'Johnson', '[email protected]', '555-123-4567', '2021-11-30', 'Designer'),
('Bob', 'Brown', '[email protected]', '555-987-6543', '2020-03-15', 'Data Analyst');
mysql2 准备
- 安装 mysql2
npm install mysql2
- 引入 mysql2
const mysql = require("mysql2/promise");
- 创建数据库连接池
const pool = mysql.createPool({
host: "localhost",
database: "testdb",
user: "root",
password: "1234",
waitForConnections: true,
connectionLimit: 10,
queueLimit: 0,
});
1、添加操作(增)
(1)演示
const insertTest = async () => {
const connection = await pool.getConnection();
try {
const [result] = await connection.execute("INSERT INTO employees (firstName, lastName, email, phone, hireDate, jobTitle) VALUES (?, ?, ?, ?, ?, ?)", [
"zhang",
"san",
"[email protected]",
"123-456-7890",
"2023-10-01",
"Developer",
]);
console.log(result);
} catch (error) {
console.error(error);
} finally {
connection.release();
}
};
insertTest();
- 输出结果
ResultSetHeader {
fieldCount: 0,
affectedRows: 1,
insertId: 5,
info: '',
serverStatus: 2,
warningStatus: 0,
changedRows: 0
}
(2)解析
-
检查
result.affectedRows
的值来判断是否有行被影响,如果 affectedRows 大于 0,则表示至少有 1 行被插入 -
如果再执行一次相同的插入,由于 email 是唯一的,会导致插入失败,会得到如下结果
Error: Duplicate entry '[email protected]' for key 'employees.email'
{
code: 'ER_DUP_ENTRY',
errno: 1062,
sql: 'INSERT INTO employees (firstName, lastName, email, phone, hireDate, jobTitle) VALUES (?, ?, ?, ?, ?, ?)',
sqlState: '23000',
sqlMessage: "Duplicate entry '[email protected]' for key 'employees.email'"
}
2、删除操作(删)
(1)演示
const deleteTest = async () => {
const connection = await pool.getConnection();
try {
const [result] = await connection.execute("DELETE FROM employees WHERE id =?", [5]);
console.log(result);
} catch (error) {
console.error(error);
} finally {
connection.release();
}
};
deleteTest();
ResultSetHeader {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
info: '',
serverStatus: 2,
warningStatus: 0,
changedRows: 0
}
(2)解析
-
检查
result.affectedRows
的值来判断是否有行被影响,如果 affectedRows 大于 0,则表示至少有 1 行被删除 -
如果再执行一次相同的删除,由于目标行已经被删除,会得到如下结果
ResultSetHeader {
fieldCount: 0,
affectedRows: 0,
insertId: 0,
info: '',
serverStatus: 2,
warningStatus: 0,
changedRows: 0
}
3、查询操作(查)
(1)演示
- 条件查询
const queryByIdTest = async () => {
const connection = await pool.getConnection();
try {
const [rows] = await connection.execute("SELECT * FROM employees WHERE id =?", [1]);
console.log(rows);
} catch (error) {
console.error(error);
} finally {
connection.release();
}
};
- 输出结果
[
{
id: 1,
firstName: 'John',
lastName: 'Doe',
email: '[email protected]',
phone: '123-456-7890',
hireDate: 2023-01-14T16:00:00.000Z,
jobTitle: 'Software Engineer'
}
]
- 全部查询
const queryAllTest = async () => {
const connection = await pool.getConnection();
try {
const [rows] = await connection.execute("SELECT * FROM employees");
console.log(rows);
} catch (error) {
console.error(error);
} finally {
connection.release();
}
};
- 输出结果
[
{
id: 1,
firstName: 'John',
lastName: 'Doe',
email: '[email protected]',
phone: '123-456-7890',
hireDate: 2023-01-14T16:00:00.000Z,
jobTitle: 'Software Engineer'
},
{
id: 2,
firstName: 'Jane',
lastName: 'Smith',
email: '[email protected]',
phone: '098-765-4321',
hireDate: 2022-07-21T16:00:00.000Z,
jobTitle: 'Product Manager'
},
{
id: 3,
firstName: 'Alice',
lastName: 'Johnson',
email: '[email protected]',
phone: '555-123-4567',
hireDate: 2021-11-29T16:00:00.000Z,
jobTitle: 'Designer'
},
{
id: 4,
firstName: 'Bob',
lastName: 'Brown',
email: '[email protected]',
phone: '555-987-6543',
hireDate: 2020-03-14T16:00:00.000Z,
jobTitle: 'Data Analyst'
}
]
(2)解析
- 检查
rows.length
的值来判断是否有行被查询到,如果 length 大于 0,则表示至少有 1 行被查询到
4、修改操作(改)
(1)演示
const updateTest = async () => {
const connection = await pool.getConnection();
try {
const [result] = await connection.execute("UPDATE employees SET firstName = ?, lastName = ? WHERE id = ?", [
"zhang",
"san",
1,
]);
console.log(result);
} catch (error) {
console.error(error);
} finally {
connection.release();
}
};
ResultSetHeader {
fieldCount: 0,
affectedRows: 1,
insertId: 0,
info: 'Rows matched: 1 Changed: 1 Warnings: 0',
serverStatus: 2,
warningStatus: 0,
changedRows: 1
}
(2)解析
-
检查
result.affectedRows
的值来判断是否有行被影响,如果 affectedRows 大于 0,则表示至少有 1 行被修改 -
如果修改不存在的目标行,会得到如下结果
ResultSetHeader {
fieldCount: 0,
affectedRows: 0,
insertId: 0,
info: 'Rows matched: 0 Changed: 0 Warnings: 0',
serverStatus: 2,
warningStatus: 0,
changedRows: 0
}