postgresqlを操作するにはnodejsを使用します

環境整備

1 navicat プレミアム
2 postgresql 14

上記のソフトウェアをインストールした後のリモート接続は次のようになります。
ここに画像の説明を挿入します
ユーザー テーブル users を作成し、ランダムにデータを生成します。

ステップ

ここでは、プロジェクトを gticode に配置します。ダウンロードして使用できます
https://gitcode.net/wangbiao9292/nodejs-postgresql/-/tree/master

ここに画像の説明を挿入します
説明するいくつかのファイルを次に示します。
1 node_modules は、
package-lock.json のロックされたバージョンに依存します
。 3 package.json の構成
4 postgresql がデータベースに接続するために使用する pgsql.js の構成
5 server.js は、express 構成に依存します。

以下のコードを貼り付けます:
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

サーバー.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)
        })
    })
    
})

次に、 npm start を実行して、
ここに画像の説明を挿入します
インターフェイス経由で値を取得します。
ここに画像の説明を挿入します
ここに画像の説明を挿入します

おすすめ

転載: blog.csdn.net/wangbiao9292/article/details/131424104