繁体   English   中英

在node.js中创建插入函数(postgresql)

[英]Create insert function (postgresql) in node.js

我正在尝试创建一个动态函数,以在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.

您有几个值应该是此行中的字符串:

insert(my_table, 3, fname, Karees)

假设my_table是表的名称, fnameKarees也是您在查询字符串中需要的值(而不是变量),您需要像这样写:

insert('my_table', 3, 'fname', 'Karees')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM