Node.js 如何将多个数据存储到postgres sql中?
我想将以下数据存储到postgres数据库中,但我不确定如何存储。我非常感谢任何帮助,因为我对postgres sql非常陌生。我知道如何单独插入,但不知道如何使用多个数据动态插入Node.js 如何将多个数据存储到postgres sql中?,node.js,postgresql,Node.js,Postgresql,我想将以下数据存储到postgres数据库中,但我不确定如何存储。我非常感谢任何帮助,因为我对postgres sql非常陌生。我知道如何单独插入,但不知道如何使用多个数据动态插入 // import database const { Client } = require('pg'); //connect to postgres const client = new Client({ "user": "postgres", "password": "root", "host": "l
// import database
const { Client } = require('pg');
//connect to postgres
const client = new Client({
"user": "postgres",
"password": "root",
"host": "localhost",
"port": "5432",
"database": "CelebrityDB"
});
data = [
{ firstName: "tom", lastName: "hanks", age: "58"},
{ firstName: "tom", lastName: "cruise", age: "51"},
{ firstName: "bradd", lastName: "pit", age: "55"},
{ firstName: "chris", lastName: "hemsworth", age: "35"},
{ firstName: "robert", lastName: "junior", age: "52"},
];
data=data.map(function(obj) {
return Object.keys(obj).sort().map(function(key) {
return obj[key];
});
});
// Insert into database
let query=format("INSERT INTO celebrity(firstName, lastName, age) VALUES %L returning id', data");
start(query);
//start function
async function start(query) {
try {
//just connect
await client.connect();
let result= await client.query(query);
console.log(result);
} catch (error) {
console.log(error);
} finally {
await client.end();
}
}
使用
pg-format
是一个非常轻量级的添加库,可以支持使用节点postgre插入多行
只需做以下更改:
pg format
提供输出转义SQL文本的%L模式
const format = require('pg-format');
将对象数组转换为数组数组,因为pg格式需要数组数组作为数据
data=data.map(function(obj) {
return Object.keys(obj).sort().map(function(key) {
return obj[key];
});
});
然后将查询存储在变量中:
let query=format("INSERT INTO celebity(firstName, lastName, age) VALUES %L returning id'", data);
然后替换此代码:
client.query("INSERT INTO celebity(firstName, lastName, age) values()");
console.log('Data has been inserted into database');
let result= await client.query(query);
console.log(result);
使用此代码:
client.query("INSERT INTO celebity(firstName, lastName, age) values()");
console.log('Data has been inserted into database');
let result= await client.query(query);
console.log(result);
您尚未在clinet.query中传递数据。您好,谢谢您的帮助!我已经根据您的建议编辑了上面的代码,但仍然不起作用。您收到的错误是什么,console.log(result)是怎么说的?它说
抛出新错误(“参数太少”)代码>函数参数错误。您已经创建了查询的字符串和要传递给函数的第二个参数。更改为格式(“插入…返回id”,数据)