Nodejs连接PostgreSQL

前端之家收集整理的这篇文章主要介绍了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

原文链接:https://www.f2er.com/postgresql/193933.html

猜你在找的Postgre SQL相关文章