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.
Can I use an arrow function in this case? Should I abandon the .prepare()
syntax and go with the examples in the webpages I linked?
EDIT: I'm using better-sqlite3
.
The examples you linked use package sqlite3
, but my guess from your code is that you're using better-sqlite3
as it is more similar to their documentation.
better-sqlite3
does not offer an API that takes an error function as the second argument of PreparedStatement.run
.
Instead, what happens is that it is trying to use your error function as a named parameter. A function is not a plain object, which explains your error.