简体   繁体   中英

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. 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. 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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