[英]How to save a GET response to a variable on ExpressJS and LocomotiveJS
[英]How to save a Javascript variable into a Mysql database in expressjs
请问我对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作为回调函数传递给您,该对象是您使用发布数据创建的对象的插入。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.