Node.js访问PostgresQL数据库
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Node.js访问PostgresQL数据库,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2986字,纯文字阅读大概需要5分钟。
内容图文
Node.js访问PostgresQL数据库,安装PostgresQL模块:进入到/usr/local/lib:发现有一个node_schedules目录,里面放的是你安装的模
1)安装PostgresQL模块:
进入到/usr/local/lib:发现有一个node_schedules目录,里面放的是你安装的模块
npm install -g node_gyp
export $PATH=$PATH:/usr/local/pgsql/bin/
npm install pg //-g 表示全局
2)连接数据库并访问
连接字符串=“tcp:// 用户名 : 密码 @localhost:5432/ 库名”;
1) 事件形式:
var pg = require('pg');
var MATH = require('math');
var constring = "tcp://postgres:1234@localhost/my";
var client = new pg.Client(constring);
client.connect();
client.query("create temp table beatle(name varchar(10),height integer)");
client.query("insert into beatle(name,height) values('john',50)");
client.query("insert into beatle(name,height) values($1,$2)",['brown',68]);
var query = client.query("select * from beatle");
query.on('row',function(row){
console.log(row);
console.log("Beatle name:%s",row.name);
console.log("beatle height:%d' %d\"",MATH.floor(row.height/12),row.height%12);
});
query.on('end',function(){
client.end();
});
测试成功,输出内容为:
{ name: 'john', height: 50 }
Beatle name:john
beatle height:4' 2"
{ name: 'brown', height: 68 }
Beatle name:brown
beatle height:5' 8"
2)回调函数形式:
var pg = require('pg');
var conString = "tcp://postgres:1234@localhost/my";
var client = new pg.Client(conString);
client.connect(function(err) {
client.query('SELECT NOW() AS "theTime"', function(err, result) {
console.log(result.rows[0].theTime);
client.end();
})
});
测试成功,输出结果为:
Wed Jan 23 2013 14:30:12 GMT+0800 (CST)
3) 用回调方式实现上面的事件形式:
var pg = require('pg');
var MATH = require('math');
var constring = "tcp://postgres:1234@localhost/my";
var client = new pg.Client(constring);
client.connect(function(err){
client.query("create temp table beatle(name varchar(10),height integer)");
client.query("insert into beatle(name,height) values('john',50)");
client.query("insert into beatle(name,height) values($1,$2)",['brown',68]);
client.query("select * from beatle ",function(err,result){
console.log(result);
for(var i=0;i<result.rowCount;i++ )
{
console.log(result.rows[i]);
console.log("Beatle name:%s",result.rows[0].name);
console.log("beatle height:%d' %d\"",MATH.floor(result.rows[0].height/12),result.rows[0].height%12);
}
client.end();
});
});
测试成功,,输出结果为:
{ command: 'SELECT',
rowCount: 2,
oid: NaN,
rows: [ { name: 'john', height: 50 }, { name: 'brown', height: 68 } ] }
{ name: 'john', height: 50 }
Beatle name:john
beatle height:4' 2"
{ name: 'brown', height: 68 }
Beatle name:john
beatle height:4' 2"
更多关于Node.js的详细信息,或者下载地址请点这里
内容总结
以上是互联网集市为您收集整理的Node.js访问PostgresQL数据库全部内容,希望文章能够帮你解决Node.js访问PostgresQL数据库所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。