29
29

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 5 years have passed since last update.

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

Posted at

公式のクライアントらしい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も多く、レイテンシも少ないっぽいですね。

29
29
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
29
29

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?