Node.js 数据库模块 mysql2

本文被收录到:

Node.js 教程

本专题关于 Node.js 基础知识和模块

目录

mysql2 是一个 Node.js 中用于连接 MySQL 数据库的模块,它是 mysql 模块的一个更快、更现代的替代品,提供了 Promise 支持和更好的性能。以下是使用 mysql2 模块进行基本数据库操作的简要教程:

安装 mysql2

首先,你需要通过 npm (Node.js 包管理器) 安装 mysql2 模块:

npm install mysql2 --save

 

简单的例子

这是一个简单的例子。

// Get the client
const mysql = require('mysql2');

// Create the connection to database
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test',
});

// A simple SELECT query
connection.query(
  'SELECT * FROM `table` WHERE `name` = "Page" AND `age` > 45',
  function (err, results, fields) {
    console.log(results); // results contains rows returned by server
    console.log(fields); // fields contains extra meta data about results, if available
  }
);

// Using placeholders
connection.query(
  'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
  ['Page', 45],
  function (err, results) {
    console.log(results);
  }
);

 

使用 Promise 包装

mysql2 包含 promise 的 API,示例:

// Get the client
import mysql from 'mysql2/promise';

// Create the connection to database
const connection = await mysql.createConnection({
  host: 'localhost',
  user: 'root',
  database: 'test',
});

// A simple SELECT query
try {
  const [results, fields] = await connection.query(
    'SELECT * FROM `table` WHERE `name` = "Page" AND `age` > 45'
  );

  console.log(results); // results contains rows returned by server
  console.log(fields); // fields contains extra meta data about results, if available
} catch (err) {
  console.log(err);
}

// Using placeholders
try {
  const [results] = await connection.query(
    'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
    ['Page', 45]
  );

  console.log(results);
} catch (err) {
  console.log(err);
}

 

使用预处理语句

以上都是使用 connection.query(),使用 connection.execute()可以完成 SQL 语句的预处理,以防止 SQL 注入的安全问题。

import mysql from 'mysql2/promise';

try {
  // create the connection to database
  const connection = await mysql.createConnection({
    host: 'localhost',
    user: 'root',
    database: 'test',
  });

  // execute will internally call prepare and query
  const [results, fields] = await connection.execute(
    'SELECT * FROM `table` WHERE `name` = ? AND `age` > ?',
    ['Rick C-137', 53]
  );

  console.log(results); // results contains rows returned by server
  console.log(fields); // fields contains extra meta data about results, if available
} catch (err) {
  console.log(err);
}

 

使用数据库连接池

数据库连接池减少数据库的连接开销。

import mysql from 'mysql2/promise';

// Create the connection pool. The pool-specific settings are the defaults
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,
});

可以与 connection 相同的方式使用池(使用pool.query() 和 pool.execute() ):

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
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);

此外,使用连接对象直接释放连接:

conn.release();

 

命名占位符

通过设置 namedPlaceholders 配置值可以为参数使用命名占位符。

connection.config.namedPlaceholders = true;
connection.execute('select :x + :y as z', { x: 1, y: 2 }, (err, rows) => {
  // statement prepared as "select ? + ? as z" and executed with [1,2] values
  // rows returned: [ { z: 3 } ]
});

connection.execute('select :x + :x as z', { x: 1 }, (err, rows) => {
  // select ? + ? as z, execute with [1, 1]
});

connection.query('select :x + :x as z', { x: 1 }, (err, rows) => {
  // query select 1 + 1 as z
});

// unnamed placeholders are still valid if the values are provided in an array
connection.query('select ? + ? as z', [1, 1], (err, rows) => {
  // query select 1 + 1 as z
});

 

错误处理

确保对查询操作进行适当的错误处理,无论是使用回调还是 async/await。

释放连接

使用连接池时,你不需要手动释放每个连接,因为查询结束后,连接会自动返回到池中。但是,如果在查询之外还需要进行其他操作(如事务),确保在操作完成后调用 connection.release() 来释放连接。

性能调优

根据实际需求调整连接池的参数,比如 connectionLimit,以达到最佳性能。监控应用和数据库性能,适时调整连接池设置,以应对不同的负载情况。

通过上述步骤,你可以有效地在 Node.js 应用中利用 mysql2 的连接池功能来管理数据库连接,提升应用性能和稳定性。

 

项目地址:https://www.npmjs.com/package/mysql2

官方文档:https://sidorares.github.io/node-mysql2/docs

修改时间 2024-08-25

声明:本站所有文章和图片,如无特殊说明,均为原创发布。商业转载请联系作者获得授权,非商业转载请注明出处。
真诚赞赏,手留余香
赞赏
搜神记
793 文章
4 教程
8 项目
随机推荐
ES6 Promise 和 async/await 教程
WordPress 文章置顶循环
Linux apt 命令
curl 的用法指南
Nginx 使用 Njs 授权访问文件
JavaScript history对象
Node.js querystring 模块
Wordpress 使用 tag 标签获取文章列表的方法