一、PostgreSQL是面向对象的RDBMS,诞生于加州大学伯克利分校

二、安装node的PostgreSQL驱动

npm install pg

三、从PostgreSQL查询数据

# 创建数据库upandrunning
sudo -u postgres createdb -O postgres upandrunning
const { Pool, Client } = require('pg')

const pool = new Pool({
  user: 'postgres',
  host: 'localhost',
  database: 'upandrunning',
  password: 'postgres',
  port: 5432,
})

pool.query('SELECT * FROM users', (err, res) => {
  console.log(err, res.rows)
  pool.end()
})

const client = new Client({
    user: 'postgres',
    host: 'localhost',
    database: 'upandrunning',
    password: 'postgres',
    port: 5432,
})
client.connect()

client.query('SELECT * FROM users', (err, res) => {
  console.log(err, res.rows)
  client.end()
})

四、插入数据到PostgreSQL

# 创建数据表
CREATE TABLE users(
   id SERIAL PRIMARY KEY     NOT NULL,
   name           CHAR(100)     NOT NULL,
   email          CHAR(100)      NOT NULL
);
const { Client } = require('pg')

const client = new Client({
    user: 'postgres',
    host: 'localhost',
    database: 'upandrunning',
    password: 'postgres',
    port: 5432,
})
client.connect()

const text = 'INSERT INTO users(name, email) VALUES($1, $2) RETURNING *'
const values = ['angus', 'gsx0312@qq.com']

client.query(text, values, (err, res) => {
  if (err) {
    console.log(err.stack)
  } else {
    console.log(res.rows[0])
    // { id: 1, name: 'angus', email: 'gsx0312@qq.com' }
  }
  client.end()
})

五、在PostgreSQL中更新数据

const { Client } = require('pg')

const client = new Client({
    host: 'localhost',
    port: 5432,
    user: 'postgres',
    password: 'postgres',
    database: 'upandrunning',
})
client.connect()

const text = 'UPDATE users SET name=$1, email=$2 WHERE name=$3'
const values = ['angela', 'GSXxg5201314@outlook.com', 'angus']

client.query(text, values, (err, res) => {
  if (err) {
    console.log(err.stack)
  } else {
    console.log(res)
  }
  client.end()
})

六、从PostgreSQL中删除数据

const { Client } = require('pg')

const client = new Client({
    host: 'localhost',
    port: 5432,
    user: 'postgres',
    password: 'postgres',
    database: 'upandrunning',
})
client.connect()

const text = 'DELETE FROM users WHERE name = $1'
const values = ['angela']

client.query(text, values, (err, res) => {
  if (err) {
    console.log(err.stack)
  } else {
    console.log(res)
  }
  client.end()
})