Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
29
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

Node.jsからMySQL接続のメモ(とnode-mysql2)

公式のクライアントらしいnode-mysqlを使います。

https://github.com/felixge/node-mysql

準備など

$ node -v
v5.5.0

$ npm init --yes
$ npm i --save mysql

Selectするだけのサンプル

app.js
'use strict';

let mysql = require('mysql');
let connection = mysql.createConnection({
  host : 'your host name',
  user : 'your user name',
  password : 'your password',
  port : 3306,
  database: 'your database name'
});

connection.connect();
connection.query('SELECT * from tabale_name LIMIT 10;', (err, rows, fields) => {
  if (err) throw err;

  console.log('The solution is: ', rows);
});

connection.end();

ちなみに node-mysql2ってのがあるらしいです。

node-mysql2というnode-mysqlよりも速いやつがあるらしいです。

fast node-mysql compatible mysql driver for node.js

$ npm i --save mysql2

読み込んでるmysqlmysql2に書き換えれば動きます。

var mysql      = require('mysql');

var mysql      = require('mysql2');

基本的には使い方に互換性があるみたいですね。

ベンチマーク

ここに計測済みデータがありました。ありがたや。

https://gist.github.com/sidorares/ffe9ee9c423f763e3b6b

Summary:

node-mysql: peaks 6000 rps, first timeout errors at 110 conns, latency99 60ms at 110 conns
node-mysql2: peak 15000 rps, first timeout errors at 150 conns, latency99 30ms at 150 conn
memory: peak 46000 rps, no erros, latency99 20ms at 300 conns (7ms at 120 conn)

と書いてあるので

node-mysqlよりもnode-mysql2の方がrpsも多く、レイテンシも少ないっぽいですね。

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
29
Help us understand the problem. What are the problem?