简体   繁体   English

如何在ExpressJS中将Javascript变量保存到Mysql数据库中

[英]How to save a Javascript variable into a Mysql database in expressjs

Please i am very new to node js and expressjs framework. 请问我对Node JS和ExpressJS框架还是很新的。 I am developing a web Application and i am stuck. 我正在开发Web应用程序,但遇到问题。 I have setup all my database requirements and all is working just fine , now i want to save some data into the database and i have the data store in a variable, but unfortunately the data stored in the variable(MyID) is not saved. 我已经设置了所有数据库要求,并且一切正常,现在我想将一些数据保存到数据库中,并且将数据存储在变量中,但是不幸的是,未保存存储在变量(MyID)中的数据。 This is my code 这是我的代码

var= MyID var = MyID

app.post("/addContact", function(req, res){ 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");

        });

});

} }

Since you have a properly formed object, you should use : 由于您具有正确形成的对象,因此应使用:

connection.query('INSERT INTO EmployeeContracts SET ?', postData, function(err, results) {
  if (err) {
    console.error(err);
  } else {
    res.redirect('/addContract');
});

This is safer and cleaner. 这样更安全更清洁。 Also, I don't think you must end the connection explicitly after the query is treated. 另外,我认为在处理查询后,您不必显式终止连接。

And to avoid your second query to be executed before the first ends, just split those in two function and pass the MyId as a callback for the insertion with the object you created with the post data. 为了避免第二个查询在第一个查询结束之前执行,只需将它们拆分为两个函数,然后将MyId作为回调函数传递给您,该对象是您使用发布数据创建的对象的插入。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM