什么是驱动程序

  1. 驱动程序是连接内存和其他存储介质的桥梁,mysql 驱动程序 是连接内存数据和 mysql 数据的桥梁;

  2. mysql 驱动程序通常使用:

    • mysql 驱动
    • mysql2 驱动

mysql2 的使用

  • createPool 创建连接池,性能更佳,无需手动关闭连接数据库;

回调的方式

const mysql = require("mysql2");

// 创建一个连接池
const pool = mysql.createPool({
  host: "localhost",
  user: "root",
  password: "123456",
  database: "test",
  multipleStatements: true,
});

// 利用 promise 的方式
pool.query(
  "SELECT * FROM `company`;",
  function (err, results) {
    console.log(results);
  });

promise 的方式

const mysql = require("mysql2/promise");

// 创建一个连接池
const pool = mysql.createPool({
  host: "localhost",
  user: "root",
  password: "123456",
  database: "test",
  multipleStatements: true,
});

// 利用 promise 的方式
const queryFn = async () => {
  const [results] = await pool.query("SELECT * FROM `company`;");
  console.log(results);
};
queryFn();

防止 sql 注入

sql 注入演示

用户通过注入 sql 语句到最终查询中,导致了整个 sql 与预期行为不符;

const mysql = require("mysql2/promise");

// 使用连接池
const pool = mysql.createPool({
  host: "localhost",
  user: "root",
  password: "123456",
  database: "test",
  multipleStatements: true,
});

async function test(id) {
  const sql = `select * from employee where \`id\` = ${id}`;
  console.log(sql);
  const [results] = await pool.query(sql);
  console.log(results);
}

// 本意是根据 id 查询员工,结果被注入的语句删除了数据
test(`1; delete from employee where id = 700;`);

变量解决 sql 注入

变量的内容不作为任何 sql 关键字,使用 ? 占位符的方式,将变量赋值给对应的占位符 ?

const mysql = require("mysql2/promise");

// 使用连接池
const pool = mysql.createPool({
  host: "localhost",
  user: "root",
  password: "123456",
  database: "test",
  multipleStatements: true,
});

async function test(id) {
  const sql = "select * from employee where \`id\` = ?;";
  const [results] = await pool.execute(sql, [id]);
  console.log(results);
}
test('1');
打赏作者
您的打赏是我前进的动力
微信
支付宝
评论

中午好👏🏻,我是 ✍🏻   疯狂 codding 中...

粽子

这有关于前端开发的技术文档和你分享。

相信你可以在这里找到对你有用的知识和教程。

了解更多

目录

  1. 1. 什么是驱动程序
  2. 2. mysql2 的使用
    1. 2.1. 回调的方式
    2. 2.2. promise 的方式
  3. 3. 防止 sql 注入
    1. 3.1. sql 注入演示
    2. 3.2. 变量解决 sql 注入