Node.jsからPostgreSQLに接続する(node-postgres)
Node.jsからPostgreSQLに接続し、データの登録や取得を試してみます。データベース
PostgreSQL 10.3を使用しました。
事前に「sample」というデータベースを作成。
以下のテーブルを作成しておきました。
CREATE TABLE test (
id int,
value text
)
node-postgres
接続にはnode-postgresを利用しました。
node-postgres
npmでライブラリをインストールします。
$ npm install pg
pg@7.4.1がインストール出来ました。
データベース接続
今回接続するデータベースは
ホスト:192.168.1.101
ユーザー:pgadmin
パスワード:P@ssw0rd
データベース:sample
です。
こちらを参考に、サンプルを作成してみます。
https://node-postgres.com/features/connecting
- const { Client } = require('pg')
- const client = new Client({
- user: 'pgadmin',
- host: '192.168.1.101',
- database: 'sample',
- password: 'P@ssw0rd',
- port: 5432,
- })
- client.connect()
- client.query('SELECT NOW()', (err, res) => {
- console.log(err, res)
- client.end()
- })
実行結果
$ node sample.js
null Result {
command: 'SELECT',
rowCount: 1,
oid: null,
rows: [ anonymous { now: 2018-04-09T07:29:16.760Z } ],
fields:
[ Field {
name: 'now',
tableID: 0,
columnID: 0,
dataTypeID: 1184,
dataTypeSize: 8,
dataTypeModifier: -1,
format: 'text' } ],
_parsers: [ [Function: parseDate] ],
RowCtor: [Function: anonymous],
rowAsArray: false,
_getTypeParser: [Function: bound ] }
ちょっとわかりにくいですが、ちゃんと実行できたようです。
すべての情報でなく、レコードの内容だけ表示してみます。
- const { Client } = require('pg')
- const client = new Client({
- user: 'pgadmin',
- host: '192.168.1.101',
- database: 'sample',
- password: 'P@ssw0rd',
- port: 5432,
- })
- client.connect()
- client.query('SELECT NOW()', (err, res) => {
- //console.log(err, res)
- console.log(res.rows[0])
- client.end()
- })
実行結果
$ node sample.js
anonymous { now: 2018-04-09T07:30:28.963Z }
ちゃんと時間が取得できていますね。
データの登録
作成したtestテーブルに値を登録してみます。
こちらを参考にしました。
https://node-postgres.com/features/queries
- const { Client } = require('pg')
- const client = new Client({
- user: 'pgadmin',
- host: '192.168.1.101',
- database: 'sample',
- password: 'P@ssw0rd',
- port: 5432,
- })
- client.connect()
- const sql = "INSERT INTO test (id, value) VALUES ($1, $2)"
- const values = [1, '日本語登録テスト']
- client.query(sql, values)
- .then(res => {
- console.log(res)
- client.end()
- })
- .catch(e => console.error(e.stack))
$[数字]がプレースフォルダーになるようです。
実行結果
$ node sample.js
Result {
command: 'INSERT',
rowCount: 1,
oid: 0,
rows: [],
fields: [],
_parsers: [],
RowCtor: null,
rowAsArray: false,
_getTypeParser: [Function: bound ] }
ちゃんとデータが登録されました。
sample=# select * from test;
id | value
----+------------------
1 | 日本語登録テスト
(1 行)
データの検索
登録したデータを検索してみます。
こちらを参考にしました。
https://node-postgres.com/features/queries
- const { Client } = require('pg')
- const client = new Client({
- user: 'pgadmin',
- host: '192.168.1.101',
- database: 'sample',
- password: 'P@ssw0rd',
- port: 5432,
- })
- client.connect()
- const query = {
- name: 'fetch-sample',
- text: 'SELECT * FROM test WHERE id = $1',
- values: [1],
- }
- client.query(query)
- .then(res => {
- console.log(res.rows[0])
- client.end()
- })
- .catch(e => console.error(e.stack))
実行結果
$ node sample.js
anonymous { id: 1, value: '日本語登録テスト' }
【参考URL】
https://node-postgres.com/
- 関連記事
-
- Node.js + d3 超初心者向けのチュートリアル
- Node.js + d3 + jsdomを使用し、サーバー側でsvgを生成
- Node.jsからPostgreSQLに接続する(node-postgres)
- Node.js CSVファイルを行ごとに読み込む(fs + readline)
- Node.js入門7 別ファイルに記載した関数の利用(module.exportsとrequire)
コメント