一、异步处理的方式
// 引入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.”);
}
}
原文地址:https://blog.csdn.net/wuxiaoquan_520/article/details/134614218
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_13803.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!