1
0

More than 3 years have passed since last update.

node.js超入門ノート5(データベース データ表示編)

Last updated at Posted at 2021-08-17

導入(データベース構築)

データベースを導入します。
今回はSQLite3を使用するので以下のコマンドでインストールします。

apt -y update
apt -y install sqlite3

次にファイルを作成します。

sqlite3 mydb.sqlite3

次のコマンドでテーブル、カラムを作成します。

create table mydata(id integer not null primary key autoincrement unique, name text not null, mail text not null,age integer);

次のコマンドでデータを挿入します。

insert into mydata values(1, 'taro', 'taro@yamada', 39);
insert into mydata values(2, 'hanako', 'hanako@flower', 28);
insert into mydata values(3, 'sachiko', 'sachiko@happy', 17);
insert into mydata values(4, 'jiro', 'jiro@change', 6);

データベース構築はひとまず終わったのでctrl+Dでデータベースから抜けます。

Expressでデータ表示(全件取得)

ExpressでSQLiteを操作するため以下のコマンドでパッケージをインストールします。

npm install sqlite3

viewsフォルダのhello.ejsを編集します。

views/hello.ejs
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="content-type" content="text/html">
        <title><%= title %></title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" crossorigin="anonymous">
        <link rel="stylesheet" href="/stylesheets/style.css" />
    </head>

    <body class="container">
        <header>
            <h1 class="display-4">
                <%= title %>
            </h1>
        </header>
        <div role="main">
            <table class="table">
                <% for(var i in content) { %>
                    <tr>
                        <% var obj = content[i]; %>
                        <th><%= obj.id %></th>
                        <td><%= obj.name %></td>
                        <td><%= obj.mail %></td>
                        <td><%= obj.age %></td>
                    </tr>
                <% } %>
            </table>
        </div>
    </body>
</html>

次にデータベースアクセスの処理を作ります。

routes/hello.js
const express = require('express');
const router = express.Router();

const sqlite3 = require('sqlite3');

// データベースオブジェクトの取得
const db = new sqlite3.Database('mydb.sqlite3');

router.get('/', (req, res, next) => {
    db.serialize(() => {
        // レコードを全て取り出す
        db.all("select * from mydata", (err, rows) => {
            // データベースアクセス完了時の処理
            if (!err) {
                var data = {
                    title: 'Hello!',
                    content: rows // 取得したレコードデータ
                };
                res.render('hello', data);
            }
        });
    });
});

module.exports = router;

以下のURLにアクセスするとデータが一覧で表示されます。

Expressでデータ表示(指定取得)

次はnode.js側で指定したデータのみ取り出します。
hello.jsを以下のように修正します。

routes/hello.js
const express = require('express');
const router = express.Router();

const sqlite3 = require('sqlite3');

// データベースオブジェクトの取得
const db = new sqlite3.Database('mydb.sqlite3');

router.get('/', (req, res, next) => {
    db.serialize(() => {
        var rows = "";
        db.each("select * from mydata", (err, row) => {
            //一つ取り出された際の処理
            if (!err) {
                rows += "<tr><th>" + row.id + "</th><td>" + row.name + "</td><td></tr>";
            }
           // 終了時の処理(countは取り出したレコード数)
        }, (err, count) => {
            if (!err){
                var data = {
                    title: 'Hello!',
                    content: rows // 取得したレコードデータ
                };
                res.render('hello', data);
            }
        });
    });
});

module.exports = router;

次にhello.ejsを修正します。

views/hello.ejs
<!DOCTYPE html>
<html lang="ja">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="content-type" content="text/html">
        <title><%= title %></title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" crossorigin="anonymous">
        <link rel="stylesheet" href="/stylesheets/style.css" />
    </head>

    <body class="container">
        <header>
            <h1 class="display-4">
                <%= title %>
            </h1>
        </header>
        <div role="main">
            <table class="table">
                <%- content %>
            </table>
        </div>
    </body>
</html>

1
0
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
1
0