我正在尝试创建一个动态函数以在node.js中的postgresql数据库中插入值。我不想单独键入查询,而是要键入函数和参数,并且它将在我调用查询时执行查询。
我要重新创建一个:
var query = "INSERT INTO my_table (id, fname) VALUES (3, 'Karees')"
我确定有正确的语法,但是我不知道它是什么。因此,我尝试像在Java中的System.out.print中那样进行操作。就是说我的表是未定义的,只要我在查询中替换它就没有问题。我想我的问题是变量引用。
我的代码:
function run(){
function insert(table, pkey, field, value){
var query = "INSERT INTO "+ table +" ("+ pkey +", "+ field +") VALUES ('"+ value +"')"
client.query(query, (err, res) => {
console.log(err, res)
client.end()
})
}
insert(my_table, 3, fname, Karees)
}
结果:
connected successfully
(node:1926828) UnhandledPromiseRejectionWarning: ReferenceError: my_table is not defined
at run (C:\Users\Johnathan Aggrey\Documents\Job\IBVAZE TECH\Spark\conn.js:27:8)
at client.connect.then.catch.finally (C:\Users\Johnathan Aggrey\Documents\Job\IBVAZE TECH\Spark\conn.js:12:16)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:68:7)
(node:1926828) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:1926828) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
答案 0 :(得分:0)
您在此行中有几个应该是字符串的值:
insert(my_table, 3, fname, Karees)
假设my_table
是表的名称,并且fname
和Karees
也是您要在查询字符串中使用的值(而不是变量),则需要这样写这个:
insert('my_table', 3, 'fname', 'Karees')