0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

シフト管理CRUDアプリ ~DBでMySQL編~

0
Last updated at Posted at 2026-01-19

参考教材

Node.jsでmysql2を取得する理由

①ORMが裏で行っている「接続管理」を最低限理解する
②実務で使うcreatePoolを使ってみる

database.jsの役割

MySQLと”つながる状態”を1回だけ作り、他のファイルから使わせるためのファイル

・poolを一つだけ作成する
・それを共有する

DBにつなぐ準備をしている裏方

全体取得までの流れ

①GET /app/shifts

②controller(getAll)

③repository(SELECT)

④database.js(pool)

MySQL

database.js

ES Modulesが今の主流

import mysql from 'mysql2';
// CommonJS版
const mysql = require('mysql2');

Promise版

mysqlの「Promise版APIを使います」という指定
mysqlをPromise(async/await)で使うための入り口をimportしている

import mysql from 'mysql2/promise';

⚠️Node.jsでPromise版を使わないなんでありえない(らしい)

MySQL接続設定

database.js
// MySQL接続設定
const pool = mysql.createPool({
  host: 'localhost',
  port: 3306,
  user: 'root',
  password: 'password',
  database: 'database',
  namedPlaceholders: true
});

応用
.env化

なぜpoolを使うのか?

namedPlaceholders

{:id} や {:email} などの名前付きのプレースホルダーが使える

shift.repository.js

DBにSQLを投げて、結果を返す

・poolのimport
・SELECT * FROM shifts
・配列を返す

①新規作成

repositories/shift.repository.js
// 新規作成 
export const createShift = async (newShift) => {
  const [result] = await pool.execute("INSERT INTO shifts(shift_date, start_time, end_time, shift_memo) VALUES (:shift_date, :start_time, :end_time, :shift_memo)",
    {
      shift_date: newShift.shift_date, 
      start_time: newShift.start_time, 
      end_time: newShift.end_time,
      shift_memo: newShift.shift_memo
    }); 
    return result;
};

②全部取得

repositories/shift.repository.js
// 全部取得
export const getAllShift = async () => {
  const [rows] = await pool.execute("SELECT * FROM shifts");
  return rows;
};

③id検索

repositories/shift.repository.js
// id検索
export const getShift = async (id) => {
  const [rowsId] = await pool.execute("SELECT * FROM shifts WHERE shiftsID = :id",  { shiftsID: id });
  return rowsId[0];
};

④シフトの更新

repositories/shift.repository.js
// 更新
export const updateShift = async (update, id) => {
  const { shift_date, start_time, end_time, shift_memo } = update;
  const [rowsUpdate] = await pool.execute("UPDATE shifts SET shift_date = :shift_date, start_time =  :start_time, end_time =  :end_time, shift_memo =  :shift_memo WHERE shiftsID = :id", { id, shift_date, start_time, end_time, shift_memo });
  return rowsUpdate;
};

⑤シフトの削除

repositories/shift.repository.js
// 削除
export const deleteShift = async (id) => {
  const [rowsDelete] = await pool.execute("DELETE FROM shifts WHERE shiftsID = :id", { shiftsID: id });
  return rowsDelete;
};
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?