LoginSignup
3
1

More than 3 years have passed since last update.

[Node.js] Node.jsを用いてMySQLにデータを登録する

Last updated at Posted at 2020-12-23

Node.jsを用いてMySQLにデータを登録する

※ 自分用の覚え書きでございます。

Node.jsを用いてMySQLにデータを登録します。ローカル環境で実行しています。

MySQLに作成したテーブル

f_id , f_name , f_age という3つのフィールドを作成しました。

007a.png

Node.js側の記述

/ (localhostのルート) にアクセスしたとき、SELECT文を実行します。
/entry に post したとき、INSERT文を実行します。

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

app.use(express.urlencoded({extended: false}));

const connection = mysql.createConnection({
  host: 'localhost',
  user: '********',
  password: '********',
  database: 'db_users'
});

app.get('/', (req, res) => {
  connection.query(
    'SELECT * FROM tbl_users',
    (error, results) => {
      res.render('index.ejs', {items: results});
    }
  );
});

app.get('/entry', (req, res) => {
  res.render('entry.ejs');
});

app.post('/entry', (req, res) => {
  connection.query(
    'INSERT INTO tbl_users (f_name, f_age) VALUES (?, ?)',
    [req.body.userName, req.body.userAge],
    (error, results) => {
      res.redirect('/');
    }
  );
});

app.listen(3000);

localhostにアクセスしたときの画面表示 : index.ejs

index.ejs
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>db_users</title>
  </head>
  <body>
    <a href="/entry">+ 新規登録</a>
    <ul>
      <li>
        <span>ID</span>
        <span>名前</span>
        <span>年齢</span>
      </li>
    </ul>
    <ul>
      <% items.forEach((item) => { %>
        <li>
          <span><%= item.f_id %></span>
          <span><%= item.f_name %></span>
          <span><%= item.f_age %></span>
        </li>
      <% }) %>
    </ul>
  </body>
</html>

/entry の画面表示 : entry.ejs

entry.ejs
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>db_users</title>
  </head>
  <body>
    <form action="/entry" method="post">
      名前:<input type="text" name="userName">
      年齢:<input type="number" name="userAge">
      <input type="submit" value="登録">
    </form>
  </body>
</html>

ブラウザからデータを登録

・localhostにアクセスします。
 →いま、2人登録されています。

008a.png

・新規登録をクリックすると入力フォームが表示されます。
 →やまださぶろう さんを登録します。

009a.png

・登録をクリックすると入力されたデータが登録、表示されます。
 →やまださぶろう さんが登録されました。

010a.png

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