1

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

1 Answer 1

2

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) {...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.