LoginSignup
3
2

More than 5 years have passed since last update.

node.jsのpg@7を使ってみた

Last updated at Posted at 2018-05-07

はじめに

node-postgres@7から記述方法が変わりました。
公式:https://node-postgres.com/

書き方

記述方法は複数あります。

  • コールバック
  • Promise
  • await/async

一番簡単なPromise方式をご紹介します。(jQueryのajax的な書き方)

  const { Pool, Client } = require('pg')

  // 接続情報定義 
  const client = new Client({
    user: 'user',
    host: 'localhost',
    database: 'db_name',
    password: 'password',
    port: 5432,
  })

  // 接続
  client.connect()

  // クエリ実行
  client.query('select * from t_todo')  // 必要であれば第二引数に配列で変数を渡す プレースホルダは$1 $2…
  .then(result => {
    console.log(result.rows[0])
    res.json(result.rows)
    client.end()
  })
  .catch(e => {
    console.error(e.stack)
    res.json({error: 'error!!!'})
    client.end()
  })

簡単に使えるので是非。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2