我正在使用pg
作为节点连接到我的Postgres服务器。
这是我在做什么:
const Pool = require('pg').Pool;
var config = {
user: "mouser",
password: "my password",
host: "somethingsomething.rds.amazonaws.com",
port: 5432,
database: "mydb",
ssl: true
}
const db = new Pool(config);
console.log("hello world")
let queryString = `CREATE TABLE IF NOT EXISTS favoritememes (id serial PRIMARY KEY, image_url varchar(255), date_favorited TIMESTAMP DEFAULT CURRENT_TIMESTAMP);`
db.query(queryString, function(err, result) {
console.log("Created table");
if (err) console.log("error", err);
});
当前,我在控制台上看到了“ hello world”,但从未打印过“ created table”,也从未看到错误。
我知道我的凭据是正确的,因为我可以使用具有相同凭据的SQLWorkbench连接到服务器。
答案 0 :(得分:0)
我认为问题在于您没有等待池完成创建。
另外,我建议使用:
exports.parameterizedPromise = parameterizedPromise.
导出parameterizedPromise 以下是如何使用参数化查询承诺的示例: / *
parameterizedPromise('SELECT * FROM foodtable f WHERE f.flavor = $1 AND f.meal = $2;', ['SPICY', 'BREAKFAST'])
.then(function(result){
console.log(result.rows);
})
.catch(function(error){
console.warn(error);
});
*/
这是我前一段时间使用的编辑版本。
const pg = require('pg');
const DBConfig = {
host: 'xxxxxx',
port: 'xxxxxx',
user: 'xxxxxx',
password: 'xxxxxx',
database: 'xxxxxx',
max: 10, // max number of clients in the pool
ssl: true,
idleTimeoutMillis: 30000 // how long a client is allowed to remain idle before being closed
};
const postgresPool = new pg.Pool(DBConfig, function(){
console.log('connected to postgres database');
// Need to wait for the pool to finish connecting before you can fire off your query.
paramaterizedPromise(`CREATE TABLE IF NOT EXISTS favoritememes (id serial PRIMARY KEY, image_url varchar(255), date_favorited TIMESTAMP DEFAULT CURRENT_TIMESTAMP);`, [])
.then(function(result){
console.log(result);
})
.catch(function(error){
console.warn(error);
});
});
postgresPool.on('error', function (err, client) {
// if an error is encountered by a client while it sits idle in the pool
// the pool itself will emit an error event with both the error and
// the client which emitted the original error
// this is a rare occurrence but can happen if there is a network partition
// between your application and the database, the database restarts, etc.
// and so you might want to handle it and at least log it out
console.error('idle client error', err.message, err.stack);
});
const paramaterizedPromise = function(query, params) {
return new Promise( function(resolve, reject){
postgresPool.connect(function(err, client, done) {
if(err) {
reject('Error Fetching Client From Pool', err);
}
client.query(query, params, function(err, result) {
//call `done()` to release the client back to the pool
done(err);
if (err){
reject(err);
} else {
resolve(result);
}
});
});
});
}