一、异步处理的方式
// 引入mysql模块
const mysql = require('mysql');
// 创建数据库连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database'
});
// 连接到数据库
connection.connect(err => {
if (err) throw err;
console.log("Connected to the database!");
});
// 插入含有单引号的字段
const text = "It's a beautiful day";
const insertQuery = 'INSERT INTO example (text_column) VALUES (?)';
connection.query(insertQuery, [text], (err, result) => {
if (err) throw err;
console.log("Record inserted:", result);
});
// 查询含有单引号的字段
const selectQuery = 'SELECT * FROM example WHERE text_column = ?';
connection.query(selectQuery, [text], (err, results) => {
if (err) throw err;
console.log("Query results:", results);
});
// 关闭数据库连接
connection.end(err => {
if (err) throw err;
console.log("Disconnected from the database.");
});
二、同步处理的方式
// 引入mysql和util模块
const mysql = require('mysql');
const util = require('util');
// 创建数据库连接
const connection = mysql.createConnection({
host: 'localhost',
user: 'your_username',
password: 'your_password',
database: 'your_database'
});
// 将 connection.connect 和 connection.query 转换为 promise 风格
const connectAsync = util.promisify(connection.connect).bind(connection);
const queryAsync = util.promisify(connection.query).bind(connection);
// 使用 async/await 来以同步的方式处理数据库操作
async function runDatabaseOperations() {
try {
// 连接到数据库
await connectAsync();
console.log("Connected to the database!");
// 插入含有单引号的字段
const text = "It's a beautiful day";
const insertQuery = 'INSERT INTO example (text_column) VALUES (?)';
const insertResult = await queryAsync(insertQuery, [text]);
console.log("Record inserted:", insertResult);
// 查询含有单引号的字段
const selectQuery = 'SELECT * FROM example WHERE text_column = ?';
const selectResults = await queryAsync(selectQuery, [text]);
console.log("Query results:", selectResults);
} catch (err) {
// 如果发生错误,打印错误信息
console.error("An error occurred:", err);
} finally {
// 无论成功还是发生错误,都断开数据库连接
connection.end();
console.log("Disconnected from the database.");
}
}