Answers:
这是我用来将node.js连接到我的Postgres数据库的示例。
我使用的node.js中的界面可以在这里https://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();
});
更新:- query.on
现在不推荐使用该函数,因此上述代码无法按预期运行。作为解决方案,请看:-query.on不是函数
一种现代而简单的方法:pg-promise:
const pgp = require('pg-promise')(/* initialization options */);
const 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';
const db = pgp(cn); // database instance;
// select and return a single 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;
});
// alternative - new ES7 syntax with 'await':
// await db.one('SELECT name FROM users WHERE id = $1', [123]);
另请参阅:如何正确声明数据库模块。
只是添加了一个不同的选项-我使用Node-DBI连接到PG,也是由于能够与MySQL和sqlite进行通信。Node-DBI还包括用于构建select语句的功能,该功能对于动态处理动态数据非常方便。
快速样本(使用存储在另一个文件中的配置信息):
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;
一种解决方案可以使用pool
如下客户端:
const { Pool } = 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
};
const pool = new Pool(config);
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);
});
您可以在此资源上看到更多详细信息。
Slonik是Kuberchaun和Vitaly提出的答案的替代方法。
Slonik实施安全的连接处理;您创建一个连接池,并为您处理连接打开/处理。
import {
createPool,
sql
} from 'slonik';
const pool = createPool('postgres://user:password@host:port/database');
return pool.connect((connection) => {
// You are now connected to the database.
return connection.query(sql`SELECT foo()`);
})
.then(() => {
// You are no longer connected to the database.
});
postgres://user:password@host:port/database
是您的连接字符串(或更典型地是一个连接URI或DSN)。
这种方法的好处是您的脚本可确保您永远不会意外离开挂起的连接。
使用Slonik的其他好处包括:
我们也可以使用postgresql-easy。它基于node-postgres和sqlutil构建。 注意: pg_connection.js和your_handler.js在同一文件夹中。db.js位于config文件夹中。
pg_connection.js
const PgConnection = require('postgresql-easy');
const dbConfig = require('./config/db');
const pg = new PgConnection(dbConfig);
module.exports = pg;
./config/db.js
module.exports = {
database: 'your db',
host: 'your host',
port: 'your port',
user: 'your user',
password: 'your pwd',
}
your_handler.js
const pg_conctn = require('./pg_connection');
pg_conctn.getAll('your table')
.then(res => {
doResponseHandlingstuff();
})
.catch(e => {
doErrorHandlingStuff()
})