如何将连接结果保存在 Node.js 中的变量中?
我们将在 node.js 中使用MySQL库中的查询函数,它将按预期返回我们的输出。使用这种方法,我们可以将连接结果保存在 Node.js 中的变量中。
设置环境和执行:
第 1 步:使用以下命令初始化节点项目。
npm init
第 2 步:打开 MySQL 数据库
第 3 步:创建 NodeJS 应用程序后,使用以下命令安装mysql模块。
npm install mysql
数据库表:我们的示例gfg_table数据库看起来像这样。
第 4 步:使用以下代码创建一个index.js文件。
index.js
const mysql = require("mysql");
var db_con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database: "gfg_db"
});
let output;
const setOutput = (rows) => {
output = rows;
console.log(output);
}
db_con.connect(async(err) => {
if (err) {
console.log("Database Connection Failed !!!", err);
return;
}
console.log("Connected to Database");
let query = 'SELECT * FROM users';
db_con.query(query, (err, rows) => {
if (err) {
console.log("internal error", err);
return;
}
// This is the important function
setOutput(rows);
});
});
第 5 步:使用以下命令运行index.js文件。
node index.js
输出: