「Node.js」pgライブラリでPostgreSQLにinsertを行うサンプル

環境
Windows 11 64bit Pro
node v16.16.0
npm 8.11.0
PostgreSQL 13.7

操作方法
1.pgライブラリをインストール

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
>npm i pg
>npm i pg
>npm i pg

2.データベース「testdb」とテーブル「usertbl」を作成します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
create table usertbl (
userid integer NOT NULL,
name varchar(10),
PRIMARY KEY (userid)
);
create table usertbl ( userid integer NOT NULL, name varchar(10), PRIMARY KEY (userid) );
create table usertbl (
  userid integer NOT NULL, 
  name varchar(10),
  PRIMARY KEY (userid)
);

3.「testdb」というデータベースに接続して、「usertbl」というテーブルにinsertを実行します。

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
const { Client } = require('pg')
const pg = new Client({
user: 'admin',
host: '0.0.0.0',
database: 'testdb',
password: 'password',
port: 5432,
})
const sql = "INSERT INTO usertbl (userid, name) VALUES ($1, $2)"
const values = [1001, 'testuser']
pg.connect()
.then(() => console.log("postgresqlに接続完了"))
.then(() => pg.query(sql, values))
.then(result => console.log(result))
.catch((err => console.log(err)))
.finally((() => pg.end()))
const { Client } = require('pg') const pg = new Client({ user: 'admin', host: '0.0.0.0', database: 'testdb', password: 'password', port: 5432, }) const sql = "INSERT INTO usertbl (userid, name) VALUES ($1, $2)" const values = [1001, 'testuser'] pg.connect() .then(() => console.log("postgresqlに接続完了")) .then(() => pg.query(sql, values)) .then(result => console.log(result)) .catch((err => console.log(err))) .finally((() => pg.end()))
const { Client } = require('pg')

const pg = new Client({
    user: 'admin',
    host: '0.0.0.0',
    database: 'testdb',
    password: 'password',
    port: 5432,
})

const sql = "INSERT INTO usertbl (userid, name) VALUES ($1, $2)"
const values = [1001, 'testuser']

pg.connect()
.then(() => console.log("postgresqlに接続完了"))
.then(() => pg.query(sql, values))
.then(result => console.log(result))
.catch((err => console.log(err)))
.finally((() => pg.end()))

 

Node.js

Posted by arkgame