「Node.js」PostgreSQLのテーブルにデータを挿入するサンプル
構文
conn.query(SQL構文) .then(result => console.log(xxx) .catch(e => console.error(e.stack))
サンプルコード
var { ConnPg } = require('pg');
var conn = new ConnPg({
user: 'root', //ユーザー名
host: 'localhost', //接続先ホスト
database: 'testdb', //データベース名
password: '12345arkgame', //パスワード
port: 5432 //ポート番号
})
conn.connect()
// SQL構文
const insertSQL = {
text: 'insert into usertable(username, useremail) VALUES($1, $2)',
values: ['user001', '123@example.com'],
}
// クエリ実行
conn.query(insertSQL)
.then(result => console.log(result.rows[0]))
.catch(e => console.error(e.stack))