What is the easiest solution to use a javascript object as values for a sqlite3 insert? The following code does not work.
JavaScript
x
14
14
1
const values = {
2
name: 'John',
3
age: 34,
4
language: 'english'
5
};
6
7
db.run('INSERT INTO tablename VALUES (?)', values, (err) => {
8
if (err) {
9
console.log(err);
10
} else {
11
console.log('success');
12
}
13
});
14
Advertisement
Answer
First of all you need to write the SQL correctly.
To insert into the columns name, age, language
,
you need to write the SQL like this:
JavaScript
1
2
1
INSERT INTO tablename (name, age, language) VALUES (?, ?, ?)
2
And pass the values of the 3 columns as parameters.
JavaScript
1
2
1
db.run('INSERT INTO tablename (name, age, language) VALUES (?, ?, ?)', [values['name'], values['age'], values['language']]), (err) => { });
2
Or if the property names in the JavaScript object correspond directly to the column names, then you can generate the correct SQL string dynamically to have more flexibility:
JavaScript
1
4
1
const cols = Object.keys(values).join(", ");
2
const placeholders = Object.keys(values).fill('?').join(", ");
3
db.run('INSERT INTO tablename (' + cols + ') VALUES (' + placeholders + ')', Object.values(values)), (err) => { });
4