什么是驱动程序
驱动程序是连接内存和其他存储介质的桥梁,mysql 驱动程序 是连接内存数据和 mysql 数据的桥梁;
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');
MySql👉 函数和分组
上一篇