简体   繁体   中英

How to Insert records on sql db using node js?

I have a post route on my node.js server and I want to send a json object on the body request to insert that on a sql database.

If I use "INSERT INTO users(UserInfo, BitMask) Values ("value1", 1)" it works, but If I try to scape the object like on the example below it doesn't.

I also tried "INSERT INTO users(UserInfo, BitMask) Values ?", [client], But it doesnt work.

  router.post("/add/client", (request, res) => {
     let client = {}
     client.UserInfo = request.body.name;
     client.BitMask = request.body.bitmask;

     pool.request().query("INSERT INTO users(UserInfo, BitMask) Values ?" + mysql.escape(client),
    (err, result)=>{
     if(!err){
         return res.json({ success: true, data: result, records_added: result.affected_rows });
        }
        return res.json({ success: false, data: err });
    })
});

This code returns the following object:

  {
    "success": false,
    "data": {
        "code": "EREQUEST",
        "number": 0,
        "originalError": {
            "sqlstate": "07002",
            "code": 0
        },
        "name": "RequestError"
        }
    }

Anyone knows what I am missing here? One of the answers I have found on google was that The problem comes from using a placeholder multiple times in a query, but it doesn't seem to be the case.

Thanks for the help.

Use a parameterized query, I'd also opt for async / await syntax for better readability

router.post("/add/client", async (request, res) => {
  try {
    const result = await pool.request()
      .input('userInfo', request.body.name)
      .input('bitmask', request.body.bitmask)
      .query("INSERT INTO users(UserInfo, BitMask) Values (@userInfo, @bitmask)");
    return res.json({ 
      success: true, 
      data: result, // I would avoid this, potential to leak DB info to the client
      records_added: result.affected_rows 
    });
  } catch (e) {
    // consider returning next(e) here and handling errors somewhere common
    return res.json({ 
      success: false, 
      data: err // don't do this, again potential to leak DB info to the client
    });
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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