1

I am new to SQL and am having a hard time writing an SQL query for my node application. I would like to use a variable in the WHERE statement, but it seems like there is more to it. This is what I have tried...

var itemID = 3;

var stmt = db.prepare("UPDATE tableName SET status = 'Out' WHERE id = itemID");
stmt.run();
stmt.finalize();

Any advice is appreciated. Thanks, Alex

2 Answers 2

4

You can also do like this,

// Directly in the function arguments.

var stmt = db.prepare("tableName SET status = ? WHERE id = ?", "out", $itemID);

// As an array.

var stmt = db.prepare("tableName SET status = ? WHERE id = ?", [ "out", $itemID ]);

// As an object with named parameters.

var stmt = db.prepare("UPDATE tableName SET status = $name WHERE id =$id", { $id: $itemID, $name: "out"});
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks! This is was exactly what I was looking for.
-3

You have to move the variable out of the string and concatenate it

var stmt = db.prepare("UPDATE tableName SET status = 'Out' WHERE id = " + itemID);

With ES6 you can use string substitution. Note the backquotes around the string instead of double quotes

var stmt = db.prepare(`UPDATE tableName SET status = 'Out' WHERE id =  ${itemID}`);

1 Comment

Brilliant! That was one of the first things I tried, but I clearly messed up the syntax. When I was googling for answers I mistakenly got the impression that there was some complicated trick to it. Thanks for the help!

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.