Nodejs连接PostgreSQL

Nodejs连接PostgreSQL

1.PostgreSQL介绍

(1)官网
https://www.postgresql.org/
(2)安装
下载安装版的,windows下傻瓜安装。。。
(3)数据库管理器
Navicat for PostgreSQL

《Nodejs连接PostgreSQL》 QQ截图20170521193014.jpg

2.Nodejs连接PostgreSQL数据库

(1)使用pg包
https://github.com/brianc/node-postgres
(2)安装
cnpm install pg --save
(3)Nodejs配置数据库

var pg = require('pg');
//数据库配置
var conString = "tcp://postgres:root@localhost/nodejspg"; //tcp://用户名:密码@localhost/数据库名
var client =  new pg.Client(conString);

(4)连接和配置数据库

var tem = 33;
//sql语句
selectSQLString = 'insert into pet(tem) values ('+tem+') ';
//客户端连接,进行数据插入
client.connect(function(error, results){
  if (error) {
    console.log('clientConnectionReady Error:'+error.message);
    client.end();
    return;
  }
  console.log('connection success...\n');
  client.query(selectSQLString,function(error,results){
    console.log(error);
  })
});

(5)数据库时间自动填充

估计是这个pg包的bug,我无法将nodejs生成的时间插入到数据库,一插入就报错。然后就百度,发现可以设置在存入字段的时候自动填充当前时间。

 alter table pet add column time timestamp without time zone not null default localtimestamp(0);

《Nodejs连接PostgreSQL》 QQ截图20170521192852.jpg

@治电小白菜20170521

    原文作者:治电小白菜
    原文地址: https://www.jianshu.com/p/45816adef36c
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞