嗨,我有以下节点代码,它可以正常工作
import express from 'express';
import connection from '../index.js'
const router = express.Router();
router.get('/allTemplates', function (req, res) {
let queryString="select count(*) as exist from users where userName='bob'";
let query = connection.query(queryString, (error, result) => {
if(error) {throw error;}
res.json(result);
})
});
module.exports = router;
我想做的就是用
if(exists==1){error='sorry but that user already exists';} else {
queryString="insert into users (userName, email, address) values('bob', 'emailAddress@email.com', 'address')";
let query = connection.query(queryString, (error, result) => {
if(error) {throw error;}
res.json(result);
})
}
我来自php背景,所以这是非常新的知识,节点的异步让我感到惊讶,但是我必须将其用于新工作。我将如何响应一个查询的结果,并根据结果运行另一个查询。
答案 0 :(得分:-1)
我将mysql库放在一个名为database的变量中,并且我正在使用async等待来运行查询。在数据库文件中,我连接到数据库并按如下所示设置变量:
const mysql = require("mysql");
const util = require("util");
const awsConfig = {
host: process.env.RDS_HOST,
user: process.env.RDS_USER,
password: process.env.RDS_PASSWORD,
database: process.env.RDS_DATABASE
};
const connection = mysql.createConnection(awsConfig);
connection.query = util.promisify(connection.query.bind(connection));
connection.end = util.promisify(connection.end.bind(connection));
module.exports = connection;
比起我,我使用async等待来运行查询,并使用结果来运行或不运行其他人。像这样:
let result;
let sqlStatement ="";
result = await database.query(sqlStatement);
let userExists = result[0].exist;
sqlStatement =
"SELECT COUNT(*) AS exist FROM user where userName=" +
database.escape(req.body.userName);
if(userExists==0){
result = await database.query("INSERT INTO user SET ?", [req.body]);
}
希望这对其他人有帮助