nodejs的pg模塊操作postgres數據庫


postgres數據庫安裝:windows安裝解壓版postgresql

 

1、使用nodejs模塊pg操作postgres數據庫

const pg = require('pg')

// 數據庫配置
var config = {
    user: "wenbin.ouyang",
    host: 'localhost',
    database: "test",
    password: "",
    port: 5432,

    // 擴展屬性
    max: 20, // 連接池最大連接數
    idleTimeoutMillis: 3000, // 連接最大空閑時間 3s
}

// 創建連接池
var pool = new pg.Pool(config);

// 查詢
pool.connect(function (err, client, done) {
    if (err) {
        return console.error('數據庫連接出錯', err);
    }
    // 簡單輸出個 Hello World
    client.query('SELECT $1::varchar AS OUT', ["Hello World"], function (err, result) {
        done();// 釋放連接(將其返回給連接池)
        if (err) {
            return console.error('查詢出錯', err);
        }
        console.log(result.rows[0].out); //output: Hello World
    });
});

pool.connect().then(client => {
    // insert 數據
    client.query("INSERT INTO student(name, age) VALUES($1::varchar, $2::int)", ["xiaoming", "20"]).then(res => {
        console.log("Insert Success")
        // 如果是自增ID,有返回值的,在res里
        return res;
    })
        .then(res => {
            // 查詢xiaoming
            return client.query("Select * FROM student WHERE name = $1", ["xiaoming"]);
        })
        .then(res => {
            // 輸出結果,看是否插入成功
            console.log(res.rows[0]) // { id: 4, name: 'xiaoming', age: 20 }
            console.log(res.rows.length)
        })
        .then(res => {
            // update 數據,將age改為21
            return client.query("UPDATE student SET age=$1 WHERE name=$2", [21, "xiaoming"])
        })
        .then(res => {
            // 再查詢一次xiaoming
            return client.query("Select * FROM student WHERE name = $1", ["xiaoming"]);
        })
        .then(res => {
            // 再輸出結果,看是否改為了21
            console.log(res.rows[0])
            console.log(res.rows.length)
        })
        .then(res => {
            // 刪除數據
            client.query("DELETE FROM student WHERE name=$1", ["xiaoming"])
        })
        .then(res => {
            // 最后再查詢一次xiaoming
            res = client.query("Select * FROM student WHERE name = $1", ["xiaoming"]);
            // 釋放連接
            client.release()
            return res
        })
        .then(res => {
            // 再輸出結果,沒數據 undefined
            console.log(res.rows[0]) // undefined
            console.log(res.rows.length) // 0
        })
})

 

2、封裝pg模塊

  dbConfig.js

const pg = require('pg')

// 數據庫配置
var config = {
    user: "wenbin.ouyang",
    host: 'localhost',
    database: "test",
    password: "root",
    port: 5432,

    // 擴展屬性
    max: 20, // 連接池最大連接數
    idleTimeoutMillis: 3000, // 連接最大空閑時間 3s
}

// 創建連接池
var pool = new pg.Pool(config)

module.exports = pool

---


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM