I have some working code to manipulate a Sqlite database written in this notation (I think ES5?):
try {
const cols = Object.keys(data).join(", ");
const placeholders = Object.keys(data).map(x => "$" + x).join(", ");
const stmt = db.prepare(`
INSERT INTO ` + table + ` (` + cols + `)
VALUES (` + placeholders + `)`);
stmt.run(data);
} catch (err) {
// some reporting and handling
}
Where the values to populate the SQL statement come from a JS object (data
) passed on earlier.
I would like to refactor this to use ES6 and replace the try...catch
block with arrow functions. I found some examples (here and here) but they use a different syntax, where the SQL command is executed directly with the .run()
method, instead of using .prepare()
as I have in my code.
However, when I try to apply an arrow function directly to my code
const cols = Object.keys(data).join(", ");
const placeholders = Object.keys(data).map(x => "$" + x).join(", ");
const insert_stmt = db.prepare(`
INSERT INTO ` + table + ` (` + cols + `)
VALUES (` + placeholders + `)`);
insert_stmt.run(data, (err) => {
if (err.message === "some error") {
// handle the error
}
});
I get the error
TypeError: Named parameters can only be passed within plain objects
From what I could understand, this is probably a syntax error? Which I think means with the new notation I’m not passing the values within the data
object correctly.
What are the best practices in a situation like this? Should I abandon the .prepare()
syntax and go with the examples in the webpages I linked?