【node.js】mysql 模块

这篇博客介绍了如何在Node.js中使用mysql模块进行数据库操作,包括建立连接、查询、插入、更新和删除数据。此外,还详细讲解了如何使用占位符以及连接池来提高性能和管理数据库连接。通过示例代码展示了如何创建连接池,以及如何在不需每次手动创建和关闭连接的情况下执行SQL查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

mysql 模块

  1. npm i mysql
  2. 引入 mysql 模块:
const mysql = require("mysql");
  1. 创建连接对象 connection
let connection = mysql.createConnection({
    host: '127.0.0.1', // 数据库的 IP 地址
    port: '3306', // 端口号,默认为 3306
    user: 'root', // 账号
    password: '000930', // 密码
    database: 'xz' // 指定要操作哪个数据库
});
  1. 创建连接:connection.connect(err => {});

  2. 断开连接:connection.end(err => {});

demo
// 引入 mysql 模块
const mysql = require("mysql");

// 创建连接对象 connection
let connection = mysql.createConnection({
    host: 'localhost',
    port: '3306',
    user: 'root',
    password: '000930',
    database: 'xz'
});

// 创建连接
connection.connect(err => {
    if (err) return err;
    console.log("成功连接");
});

// 断开连接
connection.end(err => {
    if (err) return err;
    console.log("断开连接")
});

操作数据

  • connection.connect()connection.end() 之间可以对 mysql 的数据进行操作
  • 操作语法:connection.query(sql[, sqlParams], callback)
    callback:接收 2 个参数:err - 错误信息、result - 执行结果
查询
  • select 字段 from 表名
  • 会以 Array 形式返回结果
let sql = 'select * from xz_laptop_family';
connection.query(sql, (err, result) => {
    if (err) return err;
    console.log("result", result);
});
插入
  • insert into 表名 set 字段1=值1, 字段2=值2
  • insert into 表名 values(值1, 值2):整行插入,有多少个字段就要写多少个数据,不能少
  • insert into 表名(字段1, 字段2) values(值1, 值2);:插入指定字段
  • 会以 Object 形式返回执行结果
let sql = 'insert into xz_laptop_family values(null, "小米")';
connection.query(sql, (err, result) => {
    if (err) return err;
    console.log("result", result);
});
修改
  • update 表名 set 字段1=值1, 字段2=值2 where 条件;
let sql = 'update xz_laptop_family set fname="superPhone" where fname="小米"';
connection.query(sql, (err, result) => {
    if (err) return err;
    console.log("result", result);
});
删除
  • delete from 表名 where 条件
let sql = 'delete from xz_laptop_family where fname="superPhone"';
connection.query(sql, (err, result) => {
    if (err) return err;
    console.log("result", result);
});

占位符 ?

  • ? 表示 ?? 表示 字段名 \ 表名

  • 使用单个占位符 → 可以直接传入单个数据
    使用多个占位符 → 需要以数组的形式传入多个数据

查询
let sql = 'select * from ??'; // 使用单个占位符
let sqlParams = 'xz_laptop_family';
connection.query(sql, sqlParams, (err, result) => {
    if (err) return err;
    console.log("result", result);
});
插入 demo
  • insert into 表名 set 字段1=值1, 字段2=值2
  • 使用 set 设置字段值时,字段 可以写成对象的形式
    设置多个字段 - 写入多个键值对
let sql = 'insert into xz_laptop_family set ?'; // 使用单个占位符
let sqlParams = { fname: "大米" };
connection.query(sql, sqlParams, (err, result) => {
    if (err) return err;
    console.log("result", result);
});
  • insert into 表名 values(值1, 值2):整行插入,有多少个字段就要写多少个数据,不能少
  • insert into 表名(字段1, 字段2) values(值1, 值2);:插入指定字段
let sql = 'insert into xz_laptop_family values(?)'; // 使用单个占位符
let sqlParams = "大米";
connection.query(sql, sqlParams, (err, result) => {
    if (err) return err;
    console.log("result", result);
});
修改 demo
  • update 表名 set 字段1=值1 where 条件
  • 使用 set 设置字段值时,字段 可以写成对象的形式
  • ? 表示 ?? 表示 字段名 \ 表名
let sql = 'update ?? set ? where ?? = ?'; // 使用多个占位符
let sqlParams = ["xz_laptop_family", { fname: "华为" }, "fname", "大米"];
connection.query(sql, sqlParams, (err, result) => {
    if (err) return err;
    console.log("result", result);
});
删除 demo
  • delete from 表名 where 条件
  • ? 表示 ?? 表示 字段名 \ 表名
let sql = 'delete from ?? where ?? = ?'; // 使用多个占位符
let sqlParams = ["xz_laptop_family", "fname", "华为"];
connection.query(sql, sqlParams, (err, result) => {
    if (err) return err;
    console.log("result", result);
});

连接池

  • 连接池的作用就是管理连接,提高性能
  • 使用连接池技术后,不需要每次都创建连接
    一次创建多个数据库连接,放在一个集合中,这样的数据库连接对象的集合成为连接池
使用连接池
  1. npm i mysql
  2. 引入 mysql 模块:const mysql = require("mysql");
  3. 创建连接池对象 pool
let pool = mysql.createPool({
    host: "127.0.0.1", // 数据库的 IP 地址
    port: "3306", // 端口号,默认为 3306
    user: "root", // 账号
    password: "000930", // 密码
    database: "xz", // 要操作的数据库
    connectionLimit: 10 // 连接池大小,默认为 15
});
  1. 从连接池中取出连接:pool.getConnection((err, connection) => {});
    如无连接可用,则隐式地建立一个数据库连接

  2. 关闭连接池:pool.end(err => {});

  • 当连接不再使用时,用 connection 对象的 release 方法将其归还到连接池中:
    connection.release();
  • 当一个连接不再需要使用且需要从连接池中移除时,用 connection 对象的 destroy 方法将其销毁
    connection.destroy();
demo
// 引入 mysql 模块
const mysql = require('mysql');

// 创建连接池对象
let pool = mysql.createPool({
    host: "127.0.0.1",
    port: "3306",
    user: "root",
    password: "000930",
    database: "xz",
    connectionLimit: 10
});

// 获取连接
pool.getConnection((err, connection) => {
    if (err) return err;
    console.log("成功连接");
    console.log(pool._allConnections.length); //  1

    // 查询数据
    connection.query('select * from xz_laptop_family', (err, result) => {
        if (err) return err
        console.log("result", result);
        console		.log(pool._allConnections.length); // 0
    });

    // 归还连接
    pool.end(err => {
        if (err) return err;
        console.log("断开连接")
    });
});
连接池对象 pool 也可以直接当连接对象 connection 使用,此时无需再打开、关闭连接
const mysql = require('mysql');

let pool = mysql.createPool({
    host: "127.0.0.1",
    port: "3306",
    user: "root",
    password: "000930",
    database: "xz",
    connectionLimit: 10
});

pool.query('select * from xz_laptop_family', (err, result) => {
    if (err) return err
    console.log("result", result);
});
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JS.Huang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值