认识mysql2
使用mysql2
Prepared Statement(预编译语句)
Connection Pools
Promise方式
01_mysql2的基本使用.js
const mysql = require('mysql2');
// 1.创建数据库连接
const connection = mysql.createConnection({
host: 'localhost',
port: 3306,
database: 'coderhub',
user: 'root',
password: 'Coderwhy888.'
});
// 2.执行SQL语句
const statement = `
SELECT * FROM products WHERE price > 6000;
`
connection.query(statement, (err, results, fields) => {
console.log(results);
});
02_预处理语句.js
const mysql = require('mysql2');
// 1.创建数据库连接
const connection = mysql.createConnection({
host: 'localhost',
port: 3306,
database: 'coderhub',
user: 'root',
password: 'Coderwhy888.'
});
// 2.执行SQL语句
// 在真正执行时会给?提供实际的参数才会执行
const statement = `
SELECT * FROM products WHERE price > ? AND score > ?;
`
connection.execute(statement, [6000, 7], (err, results) => {
console.log(results);
});
03_连接池的使用.js
const mysql = require('mysql2');
// 1.创建连接池
const connections = mysql.createPool({
host: 'localhost',
port: 3306,
database: 'coderhub',
user: 'root',
password: 'Coderwhy888.',
connectionLimit: 10
});
// 2.使用连接池
const statement = `
SELECT * FROM products WHERE price > ? AND score > ?;
`
connections.execute(statement, [6000, 7], (err, results) => {
console.log(results);
});
04_promise的方式.js
const mysql = require('mysql2');
// 1.创建连接池
const connections = mysql.createPool({
host: 'localhost',
port: 3306,
database: 'coderhub',
user: 'root',
password: 'Coderwhy888.',
connectionLimit: 10
});
// 2.使用连接池
const statement = `
SELECT * FROM products WHERE price > ? AND score > ?;
`
connections.promise().execute(statement, [6000, 7]).then(([results]) => {
console.log(results);
}).catch(err => {
console.log(err);
});