简体   繁体   English

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

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

I am trying to create a dynamic function to insert value in a postgresql database, in node.js. 我正在尝试创建一个动态函数,以在node.js中的postgresql数据库中插入值。 Instead of typing the queries by itself, I want to type the function and argument and it will execute the query when I call it. 我没有自己输入查询,而是想输入函数和参数,并在调用它时执行查询。

I want to recreate this: 我想重新创建:

var query = "INSERT INTO my_table (id, fname) VALUES (3, 'Karees')"

I'm sure there is a correct syntax for this but I don't know what it is. 我确信这有一个正确的语法,但我不知道它是什么。 So I tried to do it like in System.out.print in java. 所以我尝试在java中的System.out.print中这样做。 It is saying my table is undefined by if I just replace it in the query there is no problem. 它说我的表是未定义的,如果我只是在查询中替换它没有问题。 My problem I guess is the variable referencing. 我猜我的问题是变量引用。

My code: 我的代码:

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)
}

Result: 结果:

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.

You have several values that should be strings in this line: 您有几个值应该是此行中的字符串:

insert(my_table, 3, fname, Karees)

Assuming my_table is the name of your table, and fname and Karees are also values (and not variables) that you want in your query string, you need to write it like this: 假设my_table是表的名称, fnameKarees也是您在查询字符串中需要的值(而不是变量),您需要像这样写:

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

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

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