如何通过Node.js连接到Postgres
我发现自己试图创build一个postgres数据库,所以我安装了postgres,并用initdb /usr/local/pgsql/data
启动了一个服务器,然后我用postgres -D /usr/local/pgsql/data
开始了这个实例。通过节点与此交互? 例如, connectionstring
是什么,或者我怎么能够找出它是什么。
这里是我用来连接node.js到我的Postgres数据库的例子。
我使用的node.js中的接口可以在这里findhttps://github.com/brianc/node-postgres
var pg = require('pg'); var conString = "postgres://YourUserName:YourPassword@localhost:5432/YourDatabase"; var client = new pg.Client(conString); client.connect(); //queries are queued and executed one after another once the connection becomes available var x = 1000; while (x > 0) { client.query("INSERT INTO junk(name, a_number) values('Ted',12)"); client.query("INSERT INTO junk(name, a_number) values($1, $2)", ['John', x]); x = x - 1; } var query = client.query("SELECT * FROM junk"); //fired after last row is emitted query.on('row', function(row) { console.log(row); }); query.on('end', function() { client.end(); }); //queries can be executed either via text/parameter values passed as individual arguments //or by passing an options object containing text, (optional) parameter values, and (optional) query name client.query({ name: 'insert beatle', text: "INSERT INTO beatles(name, height, birthday) values($1, $2, $3)", values: ['George', 70, new Date(1946, 02, 14)] }); //subsequent queries with the same name will be executed without re-parsing the query plan by postgres client.query({ name: 'insert beatle', values: ['Paul', 63, new Date(1945, 04, 03)] }); var query = client.query("SELECT * FROM beatles WHERE name = $1", ['john']); //can stream row results back 1 at a time query.on('row', function(row) { console.log(row); console.log("Beatle name: %s", row.name); //Beatle name: John console.log("Beatle birth year: %d", row.birthday.getYear()); //dates are returned as javascript dates console.log("Beatle height: %d' %d\"", Math.floor(row.height / 12), row.height % 12); //integers are returned as javascript ints }); //fired after last row is emitted query.on('end', function() { client.end(); });
一个简单的方法: pg-promise ,如果你熟悉的是promise;)
var pgp = require('pg-promise')(/*options*/); var cn = { host: 'localhost', // server name or IP address; port: 5432, database: 'myDatabase', user: 'myUser', password: 'myPassword' }; // alternative: // var cn = 'postgres://username:password@host:port/database'; var db = pgp(cn); // database instance; // select and return user name from id: db.one('SELECT name FROM users WHERE id = $1', 123) .then(user => { console.log(user.name); // print user name; }) .catch(error => { console.log(error); // print the error; });
另请参阅: 如何正确声明数据库模块 。
只是添加一个不同的选项 – 我使用Node-DBI连接到PG,但也由于能够与MySQL和sqlite交谈。 Node-DBI还包含构buildselect语句的function,这对于dynamic地执行dynamic内容非常方便。
快速示例(使用存储在另一个文件中的configuration信息):
var DBWrapper = require('node-dbi').DBWrapper; var config = require('./config'); var dbConnectionConfig = { host:config.db.host, user:config.db.username, password:config.db.password, database:config.db.database }; var dbWrapper = new DBWrapper('pg', dbConnectionConfig); dbWrapper.connect(); dbWrapper.fetchAll(sql_query, null, function (err, result) { if (!err) { console.log("Data came back from the DB."); } else { console.log("DB returned an error: %s", err); } dbWrapper.close(function (close_err) { if (close_err) { console.log("Error while disconnecting: %s", close_err); } }); });
config.js:
var config = { db:{ host:"plop", database:"musicbrainz", username:"musicbrainz", password:"musicbrainz" }, } module.exports = config;
一个解决scheme可以使用如下的客户端pool
:
const pg = require('pg'); var config = { user: 'foo', database: 'my_db', password: 'secret', host: 'localhost', port: 5432, max: 10, // max number of clients in the pool idleTimeoutMillis: 30000 }; pool.on('error', function (err, client) { console.error('idle client error', err.message, err.stack); }); pool.query('SELECT $1::int AS number', ['2'], function(err, res) { if(err) { return console.error('error running query', err); } console.log('number:', res.rows[0].number); });
你可以在这个资源上看到更多的细节。