6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Node.js + PostgreSQL]Node.js アプリから PostgreSQL DB に接続

Posted at

書くこと

Node.js で作成したアプリから、PostgreSQL DB に接続する方法

前提条件

接続するDBは、下記記事で作成したものを利用する。
[DB/SQL]要件をテーブルに落とし込む手法のメモ書き(複式簿記のテーブル設計を例に)

フォルダ構成

NodeJSSampleApp
┣ app.js
┣ node_modules
┣ package-lock.json
┣ package.json
┣ public
┗ views
  ┗ journal.ejs

コード

app.js
const express = require('express');
const app = express();

app.use(express.static('public'));

var {Client} = require('pg');

var client = new Client({
	user: 'DB USER NAME', // DB のユーザー名を指定
	host: 'localhost',
	database: 'SampleApp',
	password: 'DB PASSWORD', // DB のパスワードを指定
	post: 5432
})

client.connect();

var query = 'select journal.id as 仕訳ID,journal.date as 日付, (select accounts_title.name from accounts_title where accounts_title.id = journal_details.debit_accounts_id) as 借方科目,journal_details.credit_amount as 借方金額,(select accounts_title.name from accounts_title where accounts_title.id = journal_details.credit_accounts_id) as 貸方科目,journal_details.credit_amount as 貸方金額,journal.memo as 摘要 from journal_details join journal on journal_details.journal_id = journal.id;';

app.get('/',(req,res)=>{

	client.query(query,(error,result)=>{
		console.log(result);
		res.render('journal.ejs',{results: result}); // results に格納した取得結果を journal.ejs で表示
		client.end();
	});
	
});

app.listen(3000);
views/journal.ejs
<html>
<head>
<title>複式簿記</title>
<link rel = "stylesheet" type="text/css" href = "/css/style.css">
<head>
<body>
<h1>複式簿記</h1>
<table>
<thead>
<tr>
<th>仕分ID</th>
<th>日付</th>
<th>借方科目</th>
<th>借方金額</th>
<th>貸方科目</th>
<th>貸方金額</th>
<th>摘要</th>
</tr>
</thead>
<% for(var i=0;i< results.rowCount;i++) {%>
<% var year = results.rows[i].日付.getFullYear(); %>
<% var month = results.rows[i].日付.getMonth() + 1; %>
<% var day = results.rows[i].日付.getDate(); %>
<tr>
<td><%= results.rows[i].仕訳id %></td>
<td><%= year + '/' + month + '/' + day %></td>
<td><%= results.rows[i].借方科目 %></td>
<td><%= results.rows[i].借方金額 %></td>
<td><%= results.rows[i].貸方科目 %></td>
<td><%= results.rows[i].貸方金額 %></td>
<td><%= results.rows[i].摘要 %></td>
</tr>
<% } %>
</table>

</body>
</html>

アプリを実行し、ブラウザから localhost:3000 にアクセス

$ cd NodeJSSampleApp
$ node app.js

表示結果

2020-05-06 16.04.52.png

6
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?