mysql2的使用

610 阅读2分钟

介绍:

  • mysql:最早的Node连接MySQL的数据库驱动;
  • mysql2:在mysql的基础之上,进行了很多的优化、改进;
  • 当前而言,我们偏向使用 mysql2 mysql2兼容了mysql的API,并且提供了一些附带功能
    • 性能更快
    • 拥有 预编译语句 (Prepared Statement)
      • 提高性能将创建的语句模块发送给MySQL,然后MySQL编译(解析、优化、转换)语句模块,并且存储它但是不执行,之后我们在真正执行时会给?提供实际的参数才会执行;就算多次执行,也只会编译一次,所以性能是更高的
      • 防止SQL注入之后传入的值不会像模块引擎那样就编译,那么一些SQL注入的内容不会被执行;or 1 = 1不会被执行;
    • 支持 promise async await 等等

安装

npm install mysql2

使用

创建连接 (通过 createConnection) 并获取连接对象

    const mysql = require("mysql2");
    // 创建连接
    const connection = mysql.createConnection({
        host: "",  // 主机地址
        port: "",  // 端口  默认为 3306
        database: "",  // 数据库名称
        user: "",  // 用户名
        password: ""  // 密码
    });

执行 SQL 语句即可 (query)

    connection.query("SELECT * FROM produce", (err, result, fields) => {
        // err 报错信息
        // result 返回结果
    });

预编译语句 (Prepared Statement) (上方有介绍 预编译语句的作用)

    const statement = `select * from produce where price > ? and break = ?`;
    connection.execute(statement, [1000, '华为'], (err, result) => {
        console.log(res);
    })

连接池 (connection Pools)

为什么需要使用到 connection Pools connection 创建的是一个连接 如果我们有多个请求的话 我们是否需要每次请求都去创建一个新的连接

连接池的作用:连接池会在需要的时候自动连接,并且不会销毁,会放到连接池中,以待后续使用 可以在创建 连接池的时候 limit 最大创建数量

    const mysql = require("mysql");
    
    const connection = mysql.createPool({
        host: "",
        port: "",
        database: "",
        user: "",
        passowrd: "",
        limit: 5  // 最大连接数量为 5
    });
    
    const statement = `select * from produce where id = ?`;
    connection.execute(statement, [1], (err, result) => {
        console.log(result);
    })

使用 promise 方式

    // 只需要将 使用 promise() 方法即可
    connection.promise().execute();