Nodejs连接PostgreSQL

时间:2022-07-23
本文章向大家介绍Nodejs连接PostgreSQL,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

Nodejs连接PostgreSQL

1.PostgreSQL介绍

(1)官网 https://www.postgresql.org/ (2)安装 下载安装版的,windows下傻瓜安装。。。 (3)数据库管理器 Navicat for 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);

QQ截图20170521192852.jpg

@治电小白菜20170521