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?

More than 1 year has passed since last update.

MySQLのテーブルのデータをJson形式で出力(エクスポート)する

Last updated at Posted at 2022-10-10

MySQLのテーブルのデータをJSONで出したくなり、その際に作ったスクリプトを紹介します。

Node.jsで書きます。

root
|- docker-compose.yml
|- node-script/
   |- package.json
   |- export-mysql-data.js
   |- db.js

まずは docker-compose ファイルを用意して、環境を整える。

docker-compose.yml
version: "3"
services:
  # #######################################
  # # Script
  # #######################################
  script:
    image: node:16
    working_dir: /usr/src/app
    volumes:
      - ./node-script/:/usr/src/app
    tty: true

  # #######################################
  # # Database (MySQL v8)
  # #######################################
  db:
    image: mysql:8.0
    command: --default-authentication-plugin=mysql_native_password
    environment:
      MYSQL_ROOT_PASSWORD: example
    ports:
      - "3306:3306"

以下のコマンドを実行

docker-compose up script db # script と db コンテナを起動
docker-compose exec script bash # script コンテナにログイン

以下のファイルを用意します。

node-script/package.json
{
  "name": "app",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "mysql": "^2.18.1"
  }
}
node-script/db.js
const mysql = require('mysql');

const localserver = mysql.createConnection({
    host: "db", //  ← DBコンテナの名前にする
    user: "root",
    password: "example",
    database: "データベース名",
});

localserver.connect(function (err) {
    if (err) throw err;
    console.log('Database Connection Ok');
});
module.exports = localserver;
node-script/export-mysql-data.js
const dbConn = require("./db");
const fs = require("fs").promises;

// 引数の sql を実行し、結果を { results } に入れて返す関数
const usePromiseQuery = ({ sql, data }) => {
  return new Promise((resolve, reject) => {
    dbConn.query(sql, data, (err, results, fields) => {
      if (err) {
        console.log("err: ", err);
        reject({ err });
      }
      resolve({ results, fields });
    });
  });
};

const run = async () => {
  console.log("start run function.");

  const { results } = await usePromiseQuery({
    sql: `SELECT * FROM sample_table`,
    data: [],
  });

  try {
    await fs.writeFile("export.json", JSON.stringify(results));
    console.log("export.json が作成されました");
  } catch (err) {
    console.log(err.toString());
  }
};

run();

ファイルの作成が完了したら、スクリプトを実行します。

node export-mysql-data.js

エラーが無ければ、
export.json が出力されるはずです。

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?