Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 9134

Node.jsでデータベース検索

$
0
0

データベースから必要な情報を検索する。
データベースはsqlite3を使用。

hello.js
router.post('/find',(req,res,next)=>{varfind=req.body.find;db.serialize(()=>{varq="select * from データベース名 where";db.all(q+find,[],(err,rows)=>{if(!err){vardata={title:'Hello/find',find:find,content:'検索条件'+find,mydata:rows}res.render('hello/find',data);}});});});

後はhtmlに以下のコードをbodyに入力して完成させる。

find.ejs
<div role="main">
        <p><%= content %></p>
        <form method="post" action="/hello/find">
            <div  class="form-group">
                <label for="find">FIND</label>
                <input type="text" name="find" id="find"
                class="form-control" value="<%=find %>">
            </div>
            <input type="submit" value="更新"
            class="btn btn-primary">
        </form>

        <table class="table mt-4">
            <% for(var i in "データベース名") { %>
            <tr>
                <% var obj = "データベース名"[i]; %>
                <th><%= obj.id %></th>
                <td><%= obj.name %></td>
                <td><%= obj.mail %></td>
                <td><%= obj.age %></td>
            </tr>
            <% } %>
        </table>
    </div>

結果
(検索前)
検索前.png
(検索後)
検索結果.png
検索条件を変えることで必要なデータを得られる。


Viewing all articles
Browse latest Browse all 9134

Trending Articles