點燈坊

失くすものさえない今が強くなるチャンスよ

對 PostgreSQL 新增資料

Sam Xiao's Avatar 2021-10-25

可將 INSERT Statement 直接傳入 Node-postgres,並且支援 Parameter 方式避免湊字串而造成 SQL Injection。

Version

Node 14.18.1
Node-postgres 8.7.1

Add Library

$ yarn add pg

pg:安裝 Node-postgres 連接 PostgreSQL。

INSERT

import PG from 'pg'

let { Pool } = PG

let pg = new Pool ({
  host: 'localhost',
  port: 5432,
  user: 'admin',
  password: '12345',
  database: 'KnexLab'
})

let { rows } = await pg.query (`
  INSERT INTO articles (title, content) 
  VALUES ($1, $2)
  RETURNING *
`, ['title 1', 'content 1'])
console.log (rows)

第 5 行

let pg = new Pool ({
  host: 'localhost',
  port: 5432,
  user: 'admin',
  password: '12345',
  database: 'KnexLab'
})

使用 Node-postgres 連接 PostgreSQL:

  • host:設定 host
  • port:設定 port
  • user:設定 id
  • password:設定 password
  • database:設定連接 database

13 行

let { rows } = await pg.query (`
  INSERT INTO articles (title, content) 
  VALUES ($1, $2)
  RETURNING *
`, ['title 1', 'content 1'])
  • INSERT 傳入 db.query
  • INSERT 的 parameter 從 $1 開始,非 $0
  • Value 須以 Array 傳入 pg.query 第二個 argument
  • INSERT 內加入 RETURING * 回傳所有新增資料,包含 id
  • pg.query 回傳為 Promise,使用 top level await 處理
  • 使用 Object Destructure 抽出 rows 才是實際回傳 Array

insert000

Conclusion

  • INSERT 一樣如 SELECT 傳入 pg.query 即可
  • pg.query 支援 Promise,因此可使用 Promise Chain 或 Async Await 處理皆可

Reference

Node-postgres, Queries