我正在运行以下代码
const {Client} = require('pg');
const credentials = {
user: "username",
host: "localhost",
database: "data",
password: "password",
port: 5432,
};
async function appendDb(val1, val2, val3) {
try {
const client = new Client(credentials);
await client.connect();
var a = await client.query(`INSERT INTO table (col1, col2, col3) VALUES (${val1}, ${val2}, ${val3})`);
await client.end();
return;
}
catch(err) {
console.log(err);
}
}
appendDb('test', 'test', 'test');
并得到以下错误
(node:17372) UnhandledPromiseRejectionWarning: Error: Connection terminated
at Connection.con.once (/usr/local/urr/node_modules/pg/lib/client.js:254:9)
at Object.onceWrapper (events.js:277:13)
at Connection.emit (events.js:194:15)
at Socket.<anonymous> (/usr/local/urr/node_modules/pg/lib/connection.js:78:10)
at Socket.emit (events.js:189:13)
at TCP._handle.close (net.js:600:12)
(node:17372) 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:17372) [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.
不知道为什么会发生这种情况,因为我正在使用catch?下面的脚本运行良好
async function clientDemo() {
try {
const client = new Client(credentials);
console.log(client);
await client.connect();
const now = await client.query("SELECT NOW()");
await client.end();
return now;
} catch(e) {
console.log(e);
}
(async () => {
const clientResult = await clientDemo();
console.log("Time with client: " + clientResult.rows[0]["now"]);
})();
所以我不认为这与无法连接到Postgres或无效的凭据或诸如此类的事情有任何关系。
尝试用这种方式查询数据库。
const {Client} = require('pg');
const credentials = {
user: "username",
host: "localhost",
database: "data",
password: "password",
port: 5432,
};
async function appendDb(val1, val2, val3) {
try {
const client = new Client(credentials);
await client.connect();
var a = await client.query('INSERT INTO table (col1, col2, col3) VALUES ($1, $2, $3)', [val1, val2, val3]);
await client.end();
return;
}
catch(err) {
console.log(err);
}
}
(async () => {
await appendDb('test', 'test', 'test');
})();