Node.js数据库驱动
2023年7月29日
安装:npm install mysql2
基本使用
query
:执行普通语句
const mysql = require('mysql2')
//1.建立连接
const connection = mysql.createConnection({
host: 'localhost',
port: 3306,
database: 'testsql',
user: 'root',
password: '123456'
})
//2.执行操作语句
const statement = 'select * from `student`;'
connection.query(statement, (err, values, fields) => {
if(err) {
console.log('查询失败:', err);
return
}
console.log(values);
console.log(fields);
})
Mysql2 支持预编译语句
execute
:执行预处理语句
const mysql = require('mysql2')
//1.建立连接
const connection = mysql.createConnection({
host: 'localhost',
port: 3306,
database: 'testsql',
user: 'root',
password: '123456'
})
//2.执行预处理语句
const statement = 'select * from `score` where c_id = ? and s_score > ?;'
connection.execute(statement, [03, 90], (err, values) => {
if(err) {
console.log('查询失败:', err);
return
}
console.log(values);
})
连接池使用
const connectionPool = mysql.createPool({
host: 'localhost',
port: 3306,
database: 'testsql',
user: 'root',
password: '123456',
connectionLimit: 5
})
Promise 写法
connectionPool.promise().execute(statement, [03, 90]).then((res) => {
const [values, fields] = res // 解构res
console.log(values);
console.log(fields);
}).catch((err) => {
console.log(err);
});
Loading...