「Node.js」PostgreSQLのテーブルにデータを挿入するサンプル

2020年11月23日

構文

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
conn.query(SQL構文)
.then(result => console.log(xxx)
.catch(e => console.error(e.stack))
conn.query(SQL構文) .then(result => console.log(xxx) .catch(e => console.error(e.stack))
conn.query(SQL構文)
  .then(result => console.log(xxx)
  .catch(e => console.error(e.stack))

サンプルコード

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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))
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))
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))

 

Node.js

Posted by arkgame