1.初始話node環(huán)境
npm init
2.安裝pg包
npm install pg --save
- 手動添加index.js 文件 并在文件中引入pg
const {Client} = require('pg');
4.輸入數(shù)據(jù)庫連接字段 并連接
const client = new Client({
user: 'postgres',
host: 'localhost', //實際數(shù)據(jù)庫地址
database: 'alandemo', //數(shù)據(jù)庫名稱
password: '123456',
port: 5432, //默認(rèn)端口
})
client.connect();
5.編寫數(shù)據(jù)庫sql腳本 執(zhí)行腳本
const sqlStr = 'SELECT * FROM sys_user'
client.query(sqlStr, (error, results) => {
if (error) {
console.log(error)
} else {
console.log(results.rows)
}
client.end()
})
6.執(zhí)行 node index
輸出:
[
{
user_id: 1,
user_name: 'admin',
nick_name: 'alan',
user_type: '00',
email: '',
phone: '',
sex: '0',
avatar: '',
password: '123456',
status: '0',
del_flag: '0',
login_ip: '',
login_date: null,
create_by: '',
create_time: null,
update_by: '',
update_time: null,
remark: null
}
]