使用Nodejs链接postgresql的两种方式
一、使用连接池的方式
var pg = require('pg'); // 数据库配置 var config = { user:"postgres", database:"test", password:"postgres", port:5432, // 扩展属性 max:20, // 连接池最大连接数 idleTimeoutMillis:3000, // 连接最大空闲时间 3s } // 创建连接池 var pool = new pg.Pool(config); // 查询 pool.connect(function(err, client, done) { if(err) { return console.error('数据库连接出错', err); } // 简单输出个 Hello World client.query('SELECT $1::varchar AS OUT', ["Hello World"], function(err, result) { done();// 释放连接(将其返回给连接池) if(err) { return console.error('查询出错', err); } console.log(result.rows[0].out); //output: Hello World }); });
二、连接客户端
const pg=require('pg') var conString = "postgres://username:password@localhost/databaseName"; var client = new pg.Client(conString); client.connect(function(err) { if(err) { return console.error('连接postgreSQL数据库失败', err); } client.query('SELECT * FROM tableName', function(err, data) { if(err) { return console.error('查询失败', err); }else{ // console.log('成功',data.rows); console.log('成功',JSON.stringify(data.rows)); } client.end(); }); });
版权声明:
作者:广州前端开发
链接:https://www.develophm.com/index.php/%e4%bd%bf%e7%94%a8nodejs%e9%93%be%e6%8e%a5postgresql%e7%9a%84%e4%b8%a4%e7%a7%8d%e6%96%b9%e5%bc%8f/808/
来源:开发之家
文章版权归作者所有,未经允许请勿转载。
THE END
二维码
共有 0 条评论