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();
});
只是添加一个不同的选项-我使用 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);
}
});
});
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]);
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)。
const createPool = require('@databases/pg');
const {sql} = require('@databases/pg');
// If you're using TypeScript or Babel, you can swap
// the two `require` calls for this import statement:
// import createPool, {sql} from '@databases/pg';
// create a "pool" of connections, you can think of this as a single
// connection, the pool is just used behind the scenes to improve
// performance
const db = createPool('postgres://localhost');
// wrap code in an `async` function so we can use `await`
async function run() {
// we can run sql by tagging it as "sql" and then passing it to db.query
await db.query(sql`
CREATE TABLE IF NOT EXISTS beatles (
name TEXT NOT NULL,
height INT NOT NULL,
birthday DATE NOT NULL
);
`);
const beatle = {
name: 'George',
height: 70,
birthday: new Date(1946, 02, 14),
};
// If we need to pass values, we can use ${...} and they will
// be safely & securely escaped for us
await db.query(sql`
INSERT INTO beatles (name, height, birthday)
VALUES (${beatle.name}, ${beatle.height}, ${beatle.birthday});
`);
console.log(
await db.query(sql`SELECT * FROM beatles;`)
);
}
run().catch(ex => {
// It's a good idea to always report errors using
// `console.error` and set the process.exitCode if
// you're calling an async function at the top level
console.error(ex);
process.exitCode = 1;
}).then(() => {
// For this little demonstration, we'll dispose of the
// connection pool when we're done, so that the process
// exists. If you're building a web server/backend API
// you probably never need to call this.
return db.dispose();
});