MySQL2
适用于Node.js的MySQL客户端,专注于性能优化。支持SQL预处理、非UTF-8编码支持、二进制文件编码支持、压缩和SSL等等 查看更多。
安装
MySQL2 可以跨平台使用,毫无疑问可以安装在 Linux、Mac OS 或 Windows 上。
- JavaScript
- TypeScript
npm install --save mysql2
npm install --save mysql2
npm install --save-dev @types/node
For TypeScript documentation and examples, see here.
查询数据
- Promise
- Callback
// 导入模块
import mysql from 'mysql2/promise';
// 创建一个数据库连接
const connection = await mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'test',
});
// 简单查询
try {
const [results, fields] = await connection.query(
'SELECT * FROM `table` WHERE `name` = "Page" AND `age` > 45'
);
console.log(results); // 结果集
console.log(fields); // 额外的元数据(如果有的话)
} catch (err) {
console.log(err);
}
// 使用占位符
try {
const [results] = await connection.query(
'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
['Page', 45]
);
console.log(results);
} catch (err) {
console.log(err);
}
// 导入模块
const mysql = require('mysql2');
// 创建一个数据库连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'test',
});
// 简单查询
connection.query(
'SELECT * FROM `table` WHERE `name` = "Page" AND `age` > 45',
function (err, results, fields) {
console.log(results); // 结果集
console.log(fields); // 额外的元数据(如果有的话)
}
);
// 使用占位符
connection.query(
'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
['Page', 45],
function (err, results) {
console.log(results);
}
);
SQL预处理的使用
使用 MySQL2,您还可以提前准备好SQL预处理语句。 使用准备好的SQL预处理语句,MySQL 不必每次都为相同的查询做准备,这会带来更好的性能。 如果您不知道为什么它们很重要,请查看这些讨论:
MySQL2 提供了 execute
辅助函数,它将准备和查询语句。 您还可以使用 prepare
/ unprepare
方法手动准备/取消准备。
- Promise
- Callback
import mysql from 'mysql2/promise';
try {
// 创建一个数据库连接
const connection = await mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'test',
});
// execute 将在内部调用 prepare 和 query
const [results, fields] = await connection.execute(
'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
['Rick C-137', 53]
);
console.log(results); // 结果集
console.log(fields); // 额外的元数据(如果有的话)
} catch (err) {
console.log(err);
}
const mysql = require('mysql2');
// 创建一个数据库连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'test',
});
// execute 将在内部调用 prepare 和 query
connection.execute(
'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
['Rick C-137', 53],
function (err, results, fields) {
console.log(results); // 结果集
console.log(fields); // 额外的元数据(如果有的话)
}
);
如果再次执行相同的语句,他将从缓存中选取,这能有效的节省准备查询时间获得更好的性能。
连接池的使用
连接池通过重用以前的连接来帮助减少连接到 MySQL 服务器所花费的时间,当你完成它们时让它们保持打开而不是关闭。
这改善了查询的延迟,因为您避免了建立新连接所带来的所有开销。
- Promise
- Callback
import mysql from 'mysql2/promise';
// 创建连接池,设置连接池的参数
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'test',
waitForConnections: true,
connectionLimit: 10,
maxIdle: 10, // max idle connections, the default value is the same as `connectionLimit`
idleTimeout: 60000, // idle connections timeout, in milliseconds, the default value 60000
queueLimit: 0,
enableKeepAlive: true,
keepAliveInitialDelay: 0,
});
const mysql = require('mysql2');
// 创建连接池,设置连接池的参数
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'test',
waitForConnections: true,
connectionLimit: 10,
maxIdle: 10, // max idle connections, the default value is the same as `connectionLimit`
idleTimeout: 60000, // idle connections timeout, in milliseconds, the default value 60000
queueLimit: 0,
enableKeepAlive: true,
keepAliveInitialDelay: 0,
});
该池不会预先创建所有连接,而是根据需要创建它们,直到达到连接限制。
您可以像直接连接一样使用池(使用 pool.query()
和 pool.execute()
):
- Promise
- Callback
try {
// For pool initialization, see above
const [rows, fields] = await pool.query('SELECT `field` FROM `table`');
// Connection is automatically released when query resolves
} catch (err) {
console.log(err);
}
// For pool initialization, see above
pool.query('SELECT `field` FROM `table`', function (err, rows, fields) {
// Connection is automatically released when query resolves
});
或者,也可以手动从池中获取连接并稍后返回:
- Promise
- Callback
// For pool initialization, see above
const conn = await pool.getConnection();
// Do something with the connection
await conn.query(/* ... */);
// Don't forget to release the connection when finished!
pool.releaseConnection(conn);
// For pool initialization, see above
pool.getConnection(function (err, conn) {
// Do something with the connection
conn.query(/* ... */);
// Don't forget to release the connection when finished!
pool.releaseConnection(conn);
});
-
Additionally, directly release the connection using the
connection
object:conn.release();
Promise封装
MySQL2 也支持 Promise API。 这与 ES7 异步等待非常有效。
import mysql from 'mysql2/promise';
async function main() {
// create the connection
const connection = await mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'test',
});
// query database
const [rows, fields] = await connection.execute(
'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
['Morty', 14]
);
}
MySQL2 使用范围内可用的默认 Promise
对象。 但是你可以选择你想使用的 Promise
实现。
// 导入模块
import mysql from 'mysql2/promise';
// get the promise implementation, we will use bluebird
import bluebird from 'bluebird';
// create the connection, specify bluebird as Promise
const connection = await mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'test',
Promise: bluebird,
});
// query database
const [rows, fields] = await connection.execute(
'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
['Morty', 14]
);
MySQL2 还在 Pools 上公开了一个 .promise()
函数,因此您可以从同一个池创建一个 promise/non-promise 连接。
import mysql from 'mysql2';
async function main() {
// create the pool
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
database: 'test',
});
// now get a Promise wrapped instance of that pool
const promisePool = pool.promise();
// query database using promises
const [rows, fields] = await promisePool.query('SELECT 1');
}
MySQL2 在 Connections 上公开了一个 .promise()
函数,以“升级”现有的 non-promise 连接以使用 Promise。
const mysql = require('mysql2');
// create the connection
const conn = mysql.createConnection({
host: 'localhost',
user: 'root',
database: 'test',
});
conn
.promise()
.query('SELECT 1')
.then(([rows, fields]) => {
console.log(rows);
})
.catch(console.log)
.then(() => conn.end());
结果返回
如果你有两个相同名称的列,你可能希望以数组而不是对象的形式获取结果,为了防止冲突,这是与 Node MySQL 库的区别。
例如: SELECT 1 AS `foo`, 2 AS `foo`
.
您可以在连接级别(适用于所有查询)或查询级别(仅适用于该特定查询)启用此设置。
连接级别
- Promise
- Callback
const conn = await mysql.createConnection({
host: 'localhost',
database: 'test',
user: 'root',
rowsAsArray: true,
});
const conn = mysql.createConnection({
host: 'localhost',
database: 'test',
user: 'root',
rowsAsArray: true,
});
查询级别
- Promise
- Callback
try {
const [results, fields] = await conn.query({
sql: 'SELECT 1 AS `foo`, 2 AS `foo`',
rowsAsArray: true,
});
console.log(results); // 返回数组而不是数组对象
console.log(fields); // 无变化
} catch (err) {
console.log(err);
}
conn.query(
{
sql: 'SELECT 1 AS `foo`, 2 AS `foo`',
rowsAsArray: true,
},
function (err, results, fields) {
console.log(results); // in this query, results will be an array of arrays rather than an array of objects
console.log(fields); // fields are unchanged
}
);
Need help? Ask your question on Stack Overflow or GitHub. If you've encountered an issue, please file it on GitHub.