我对node js和expressjs框架很陌生。我正在开发一个web应用程序,我被卡住了。我已经设置了所有的数据库要求,所有的工作都很好,现在我想把一些数据保存到数据库中,我把数据存储在一个变量中,但不幸的是,存储在变量(MyID)中的数据没有保存。这是我的密码
var=MyID
app.post(“/AddContact”,function(req,res){
var postData = {
// MyID: req.body.txtemplyeeID************Get employee ID as a foreign Key and Insert it,
EmployeeID:req.body.txtemployeeID,
FatherName:req.body.txtfathersName,
MotherName:req.body.txtMothersName,
NameOfSpouse:req.body.txtSpouseName,
SpouseAddress:req.body.txtSpouseAddress,
ParentsAddress:req.body.txtParentsAddress,
EmployeeAddress:req.body.txtEmployeeAddress
};
connection.connect();
connection.query('SELECT MyID from employees where EmployeeID='+"'"+ postData.EmployeeID +"'" +'', function(err, rows, fields) {
if (err) throw err;
for (var i in rows)
{
var results = rows[i];
MyID=results.MyID;
console.log(MyID);
}
})
connection.query('INSERT INTO EmployeeContacts(MyID,FatherName,MotherName,NameOfSpouse,SpouseAddress,ParentsAddress,EmployeeAddress) VALUES ('+"'"+ MyID +"'"+','+"'"+ postData.FatherName +"'" +','+"'"+ postData.MotherName +"'" +','+"'"+ postData.NameOfSpouse +"'" +','+"'"+ postData.SpouseAddress +"'" +','+"'"+ postData.ParentsAddress +"'" +','+"'"+ postData.EmployeeAddress +"'" +');',
function(err,results){
if(err)console.log(err);
else
console.log("Success");
connection.end() ;
res.redirect("/addContact");
});
});
}
由于您有一个格式正确的对象,因此应该使用:
connection.query('INSERT INTO EmployeeContracts SET ?', postData, function(err, results) {
if (err) {
console.error(err);
} else {
res.redirect('/addContract');
});
这样更安全更干净。还有,我不认为您必须在处理查询之后显式地结束连接。
为了避免在第一个查询结束之前执行第二个查询,只需将这些查询拆分为两个函数,并将MyId作为回调传递给使用post数据创建的对象进行插入。