LoginSignup
14
11

More than 5 years have passed since last update.

Node.jsでMySQLを利用する方法

Posted at

Node.jsでMySQLを利用する際の方法をいかに記載する。

前提

以下の前提で手順を記載する。

利用するMySQLの格納先:localhost
作成ユーザ:node
パスワード:pw

手順

DBを作成する。

CREATE DATABASE yamamoto;

image.png

DBの作成結果を確認する。

show databases;

image.png

作成したDBを利用出来るようにする。

use yamamoto;

image.png

テーブルを作成する。

CREATE TABLE pet (name VARCHAR(20), birth DATE, death DATE);

image.png

テーブルの作成結果を確認する。

show tables;

image.png

テーブル定義を確認する。

describe pet;

image.png

サンプルレコードを登録する。

insert into pet (name,birth) values ('hana',20180929);

image.png

登録結果を確認する。

select * from pet;

image.png

ユーザを作成する。

ユーザ作成コマンド
create user 'node'@'localhost' identified with mysql_native_password by 'pw';

ユーザを作成する際に「mysql_native_password」を付与しないと、他システムから作成したユーザでアクセスが出来ないので必ず付与すること。
image.png

ユーザが作成されたか確認する。

SHOW GRANTS for 'node'@'localhost';

image.png

参照等可能テーブルを指定する。

GRANT ALL ON yamamoto.* to node@localhost;

image.png

権限の付与結果を確認する。

SHOW GRANTS for 'node'@'localhost';

image.png

node.jsに以下のプログラムを記載する。

var http = require('http');
var fs = require('fs');
var querystring = require('querystring');
var path = require('path');
var url = require('url');
var mime = {
    ".html": "text/html",
    ".css": "text/css"
    // 読み取りたいMIMEタイプはここに追記
};
// requireの設定
var mysql = require('mysql');

// MySQLとのコネクションの作成
var connection = mysql.createConnection({
    host: 'localhost',
    port: 3306,
    user: 'node',
    password: 'pw',
    database: 'yamamoto'
});

var server = http.createServer(function (req, res) {

    console.log('req.url : ' + req.url);
    console.log('req.method : ' + req.method);

    if (req.url === '/' && req.method === 'GET') {
        // 接続
        connection.connect(function (err) {
            if (err) {
                console.error('error connecting: ' + err.stack);
                return;
            }
            console.log('connected as id ' + connection.threadId);
        });

        // userdataの取得
        connection.query('SELECT * from pet;', function (err, rows, fields) {
            if (err) { console.log('err: ' + err); }

            console.log('name: ' + rows[0].name);
            console.log('birth: ' + rows[0].birth);
            console.log('death: ' + rows[0].death);

        });
        // 接続終了
        connection.end();
        res.end('OK');

    }
});

// localhostの8000番ポートでサーバーを起動する
var port = process.env.PORT || 8000;
server.listen(port, function () {
    console.log("To view your app, open this link in your browser: http://localhost:" + port);
});

node.jsを起動する。

起動してMySQLから値を取得した結果は以下の通り。
image.png

14
11
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
14
11