Environmental preparation
1 navicat premium
2 postgresql 14
After installing the above software, the remote connection is as follows:
Create a user table users yourself, and then randomly generate some data.
step
Here I put the project in gticode, which can be downloaded and used
https://gitcode.net/wangbiao9292/nodejs-postgresql/-/tree/master
Here are a few files to explain:
1 node_modules depends on
2 package-lock.json locked version
3 package.json configuration
4 pgsql.js configuration used by postgresql to connect to the database
5 server.js depends on express configuration
Paste the code below:
pgsql.js
var pg = require("pg");
class pgsql {
pool;
constructor() {
this.pool = new pg.Pool({
database: "demo", //数据库名称
user: "postgres", //用户名
password: "root", //密码
port: 5432, //端口号
// 扩展属性
max: 20, // 连接池最大连接数
idleTimeoutMillis: 3000 // 连接最大空闲时间 3s
})
}
//查询数据
searchData(sqlString,callback){
this.pool.connect((err,client,done)=>{
client.query(sqlString,(err,result)=>{
console.log(result)
})
})
}
}
module.exports = pgsql
server.js
const pgsql = require("./pgsql")
const express = require('express');
const app = express();
const port = 5422;
app.listen(port, () => console.log(`listening on http://localhost:${
port}`));
/**
* 根路径访问
*/
app.get("/",(req,res)=>{
res.send("hello world")
})
/**
* 获取用户表信息
*/
app.get("/user",(req,res)=>{
var sqlString = "select * from users";
var s = new pgsql();
s.pool.connect((err,client,done)=>{
client.query(sqlString,(err,result)=>{
done();
console.log(result.rows)
res.send(result)
})
})
})
Then run npm start
to get the value through the interface: