How to connect to PostgreSQL?
Can someone provide a complete working sample of how to connect to a PostgreSQL database, including a correctly formatted connectionstring?
I've setup a database with the name 'Publish' with a table named 'pages' with two records, and a user of 'postgres' with the password 'root' and using this:
(in defintion file)
...
require('sqlagent/pg').init({
host: "localhost",
database: "Publish",
user: "postgres",
password: "root",
port: 5432
}, true);
...
(in model)
const sql = DATABASE( new ErrorBuilder() );
sql.select('result', 'pages').make(function ( builder ) {
builder.where('id', '>', 0);
});
sql.exec(function ( err, response ) {
console.log("Server err", err);
console.log("Server response", response);
$.callback( response.result );
});
I get this output:
err { items:
[ { name: '',
error: 'error: database "Publish" does not exist',
path: undefined,
index: undefined,
prefix: undefined } ],
transformName: undefined,
onResource: [Function],
resourceName: undefined,
resourcePrefix: '',
isResourceCustom: false,
count: 1,
replacer: [],
isPrepared: false,
contentType: 'application/json',
status: 200,
unexpected: true }
Server response {}
I know the database exists and Postgres is running, but am I connecting to the right instance of PostegreSQL or (anything else wrong)?
Also tried this: require('sqlagent/pg').init('postgresql://postgres:[email protected]/Publish', true);
and this:
require('sqlagent/pg').init('postgresql://postgres:[email protected]:5432/Publish', true);
No luck either.
Hi,
just to make sure the database exists you can run psql --list to get a list of dbs.
All 3 ways you tried are correct connection strings/objects and since you get the error from db it means it connected correctly.
You asked am I connecting to the right instance so just make sure only single instance is running and you should know the correct port it is running on. If you have multiple db instances running and you are not sure which you are connecting to it's really hard to help.
You can also try the connection without sqlagent. Create a dbtest.js with content bellow in your app folder and run it node dbtest
var Client = require('pg').Client
var client = new Client({
host: "localhost",
database: "Publish",
user: "postgres",
password: "root",
port: 5432
})
client.connect((err) => {
if (err) {
console.error('connection error', err.stack)
} else {
console.log('connected')
}
})