1.安装pg
cnpm install pg -g
2.连接pg
使用连接池的方式:
var pgsql = require('pg');
var connection = pgsql.Pool({
host : 'localhost',
port : 5432,
user : 'postgres',
password : 'admin',
database : 'ben'
});
connection.connection();
var sql=" SELECT * from weather";
connection.query(sql, function (err, results, fields) {
if(err){
console.log(err.message);
return;
}
console.log('--------------------------SELECT----------------------------');
console.log(results);
console.log('------------------------------------------------------------\n\n');
});
连接客户端:
const pg=require('pg')
var conString = "postgres://username:password@localhost:port/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();
});
});
数据库操作
- 查询
var sql=" SELECT * from weather";
connection.query(sql, function (err, results, fields) {
if(err){
console.log(err.message);
return;
}
console.log('--------------------------SELECT----------------------------');
console.log(results);
console.log('------------------------------------------------------------\n\n');
});
- 插入数据
var addSql = 'INSERT INTO weather(city,temp_lo,temp_hi,prcp,date) VALUES(
$1,$2,$3,$4,$5
)';
//注意:必须是$1,$2,$3,$4,$5
var addSqlParams = ['nodejs',12,23,0.32,'2019-2-27'];
connection.query(addSql,addSqlParams,function (err, result) {
if(err){
console.log(err);
return;
}
console.log('--------------------------INSERT----------------------------');
//console.log('INSERT ID:',result.insertId);
console.log('INSERT ID:',result);
console.log('-----------------------------------------------------------------\n\n');
});
- 更新
var addSql = 'UPDATE weather SET temp_hi = temp_hi - 2, temp_lo = temp_lo - 2 WHERE date > 1,3,5`
var addSqlParams = ['1994-11-28'];
connection.query(addSql,addSqlParams,function (err, result) {
if(err){
console.log(err);
return;
}
//console.log('INSERT ID:',result.insertId);
console.log(result);
console.log('-----------------------------------------------------------------\n\n');
});
- 删除
var addSql = 'DELETE FROM weather WHERE city=1,3,5`
var addSqlParams = ['ben'];
connection.query(addSql,addSqlParams,function (err, result) {
if(err){
console.log(err);
return;
}
//console.log('INSERT ID:',result.insertId);
console.log(result);
console.log('-----------------------------------------------------------------\n\n');
});
https://www.cnblogs.com/always-online/p/3529727.html
http://www.runoob.com/nodejs/nodejs-mysql.html