mysqlnode.jsnode-mysql

How do I insert a JS Object into a mysql row (in nodeJS)?


Right now I use this cumbersome approach when I want to add a row whose data is in a JS Object

Adding a row to a table:

const mysql = require('mysql')
var db = mysql.createConnection(DBInfo)

var databaseObj = {val1: '1', name: 'John', age: 40} // row to insert

var query = 'INSERT INTO my_table ('
var databaseKeys = Object.keys(databaseObj)
for (let i = 0; i < databaseKeys.length; i++) {
  query += databaseKeys[i] + (i !== databaseKeys.length - 1 ? ', ' : ')')
}
query += ' ' + 'VALUES('
for (let i = 0; i < databaseKeys.length; i++) {
  query += '\'' + databaseObj[databaseKeys[i]] + '\'' + (i !== databaseKeys.length - 1 ? ', ' : ')')
}

db.query(query, function (err, results, fields) {...

Is there any simpler or neater way to add a row into a table, where such row data is in a JS Object? The examples I see around use an array of arrays, but in my case the info is in a Object


Solution

  • I should use the INSERT into table SET because they are equivalent

    var db = mysql.createConnection(DBInfo)
    
    var databaseObj = {val1: '1', name: 'John', age: 40}
    
    var query = 'INSERT INTO my_table SET ' + db.escape(databaseObj)
    db.query(query, function (err, results, fields) {...