使用pg连接PostgreSQL数据库
- 服务器安装PostgreSQL(以Ubuntu系统为例,已安装docker的情况下)
docker pull postgres
docker images
docker run --name postgress -e POSTGRES_PASSWORD=postgres -e POSTGRES_USER=postgres -d -p 5433:5432
- 安装pg
npm install pg -g
npm install pg --save
- 使用连接池链接数据库
const pg = require('pg');
const pgConfig = {
user: 'postgres',
database: 'postgres',
password: 'postgres',
host: '10.20.30.40',
port: '5433'
};
const pool = new pg.Pool(pgConfig);
- 查表请求数据
const pg = require('pg');
const pgConfig = {
user: 'postgres',
database: 'postgres',
password: 'postgres',
host: '10.20.30.40',
port: '5433'
};
const pool = new pg.Pool(pgConfig);
pool.connect(function(error, client, done) {
let sqlStr = 'SELECT * FROM test';
client.query(sqlStr, [], function(err, response) {
done();
console.log(response.rows)
})
})