nodejs连接postgreSQL数据库

nodejs连接pg数据库有两种方式,一种是直接连接、操作、断开

还有一种是使用连接池,这种方式可以有效提升多并发的效率

下边是使用两种不同方式的测试代码:

 

var pgOpt = require('pg');
/*
 * 使用连接池
 * */
function connectPgWithPool() {
    var pgConfig = {
        user: 'postgres',
        database: 'postgres',
        password: '123456',
        host: '192.168.1.234',
        port: '5432',
        poolSize: 5,
        poolIdleTimeout: 30000,
        reapIntervalMillis: 10000
    };
    var pgPool = new pgOpt.Pool(pgConfig);
    // var pgPool = new pgOpt.pools.getOrCreate(pgConfig);// 低版本的pg模块需要这样来创建连接池
    
    pgPool.connect(function (isErr, client, done) {
        if (isErr) {
            console.log('connect query:' + isErr.message);
            return;
        }
        client.query('select now();', [], function (isErr, rst) {
            done();
            if (isErr) {
                console.log('query error:' + isErr.message);
            } else {
                console.log('query success, data is: ' + rst.rows[0].now);
            }
        })
    });
}
/** 不使用连接池* */
function connectPgWithoutPool() {
    var conStr = "postgres://postgres:123456@192.168.1.234:5432/postgres";
    var client = new pgOpt.Client(conStr);
    client.connect(function (isErr) {
        if (isErr) {
            console.log('connect error:' + isErr.message);
            client.end();
            return;
        }
        client.query('select now();', [], function (isErr, rst) {
            if (isErr) {
                console.log('query error:' + isErr.message);
            } else {
                console.log('query success, data is: ' + rst.rows[0].now);
            }
            client.end();
        })
    })
}
connectPgWithPool();
//connectPgWithoutPool();

 

 

 

 

 

转载自:https://blog.csdn.net/u013992330/article/details/79281250

You may also like...