我在一个名为stock_quantity的表中有一列。每条记录都有一个特定的数字,表示当前库存中的库存量。我正在使用节点查询器提示用户输入要添加到现有stock_quantity记录的金额。我想更新stock_quantity的具体记录,而不必查询数据库以获得现有的库存数量。是否可以或者我必须执行单独的查询以获取特定的现有数量,然后在更新查询之前进行数学运算?
如果我使用以下代码段,我可以按特定金额更新记录(例如1):
connection.query("UPDATE product SET stock_quantity = stock_quantity + 1
WHERE ?",
[
{
item_id: itemID
}
],
function(err, result) {
if(err) {
console.log(err);
}
console.log("Stock Quantity of item " + itemID + " increased by " +
addQty + " units.");
}
);
但是,如果我尝试以可变数量更新stock_quantity的记录,我会收到错误消息。我尝试了以下内容:
var itemID = parseInt(answer.item_id);
var addQty = parseInt(answer.add_qty);
if(typeof addQty === "number") {
connection.query("UPDATE product SET stock_quantity = stock_quantity +
addQTY WHERE ?",
[
{
item_id: itemID
}
],
function(err, result) {
if(err) {
console.log(err);
}
console.log(result);
console.log("Stock Quantity of item " + itemID + " increased by " +
addQty + " units.");
}
);
}
我也试过这个:
var itemID = parseInt(answer.item_id);
var addQty = parseInt(answer.add_qty);
if(typeof addQty === "number") {
connection.query("UPDATE product SET ? WHERE ?",
[
{
stock_quantity: stock_quantity + addQty
},
{
item_id: itemID
}
],
function(err, result) {
if(err) {
console.log(err);
}
console.log(result);
console.log("Stock Quantity of item " + itemID + " increased by " +
addQty + " units.");
}
);
}
最后,我尝试了这个:
var itemID = parseInt(answer.item_id);
var addQty = parseInt(answer.add_qty);
if(typeof addQty === "number") {
connection.query("UPDATE product SET stock_quantity = stock_quantity + ?
WHERE ?",
[
{
addQty
},
{
item_id: itemID
}
],
function(err, result) {
if(err) {
console.log(err);
}
console.log(result);
console.log("Stock Quantity of item " + itemID + " increased by " +
addQty + " units.");
}
);
}
答案 0 :(得分:0)
您可以连接SQL字符串的添加内容(即使我不建议使用参数,但是您可以控制该值):
import os
import csv
import pyodbc
import datetime
from dateutil.relativedelta import relativedelta
try:
conn = pyodbc.connect(
r'DRIVER={ODBC Driver 13 for SQL Server};'
r'SERVER=blah;'
r'DATABASE=blah;'
r'Trusted_Connection=yes;'
)
except pyodbc.Error:
conn = pyodbc.connect(
r'DRIVER={ODBC Driver 11 for SQL Server};'
r'SERVER=blah;'
r'DATABASE=blah;'
r'Trusted_Connection=yes;'
)
cursor = conn.cursor()
cursor.execute("Select * From Table1")
dData = cursor.fetchall()
或者,如果您始终按connection.query("UPDATE product SET stock_quantity = stock_quantity + " + addQTY + " WHERE ?",
[
{
item_id: itemID
}
],
...
进行检查,则可以参数化查询:
item_id