node.js PostgreSQLにselectをasync/awaitで実行する
- 2021.03.02
- PostgreSQL
- node.js, PostgreSQL

node.jsのライブラリ「pg」でPostgreSQLにselectをasync/awaitで実行するサンプルコードを記述してます。nodeのバージョンは14.15.1となります。
環境
- OS Ubuntu 20.10
- node V14.15.1
- npm 6.14.9
- PostgreSQL 13.1
pgインストール
pgを使用して、接続するので、npmでインストールしておきます。
1 |
npm i pg |
async/awaitで実行
事前に「sample」データベースの「numbers」テーブルにデータを挿入しておきます。
1 2 |
INSERT INTO numbers (id, name) VALUES (1,'mebee') INSERT INTO numbers (id, name) VALUES (2,'info') |
以下は、thenを使用して、「numbers」テーブルのデータをselectを実行してデータを取得するサンプルコードとなります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
const { Client } = require('pg') const pg = new Client({ user: 'mebee', host: '0.0.0.0', database: 'sample', password: 'password', port: 5432, }) const query = { name: 'hoge', text: 'SELECT * FROM numbers' } pg.connect() .then(() => console.log("接続完了")) .then(() => pg.query(query)) .then(result => console.table(result.rows)) .catch((err => console.log(err))) .finally((() => pg.end())) |
これをasync/awaitを使用して記述すると、以下のコードになります。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
const { Client } = require('pg') const pg = new Client({ user: 'mebee', host: '0.0.0.0', database: 'sample', password: 'password', port: 5432, }) const sample = async () => { try { await pg.connect() console.log('接続完了') const results = await pg.query("select * from numbers") console.table(results.rows) } catch (e) { console.log(e) } finally { await pg.end() } } sample() |
実行結果
1 2 3 4 5 6 7 |
接続完了 ┌─────────┬────┬─────────┐ │ (index) │ id │ name │ ├─────────┼────┼─────────┤ │ 0 │ 1 │ 'mebee' │ │ 1 │ 2 │ 'info' │ └─────────┴────┴─────────┘ |
-
前の記事
git merge実行時に「Please enter a commit message to explain why this merge is necessary」が表示される 2021.03.02
-
次の記事
SQL Server2019 エラー「要求が失敗したか、サービスが適切な時間内に応答しませんでした。」が発生したい場合 2021.03.02
コメントを書く