DRYな備忘録

Don't Repeat Yourself.

deprecated: connect() is now done automatically.【node.js】【mysql】【express】

【問題】

node.js のフレームワークExpressの中で、mysqlを使いたい。

$ npm install mysql

してきて、

server.js全文

 var Client = require('mysql').Client;
 function mysql(cb){ 
     var client = new Client(); 
     client.database = 'sampleDatabase'; 
     client.user     =     'sampleUser'; 
     client.password = 'samplePassword'; 
  
     client.connect(function(err){ 
         if(err) throw err; 
         cb(client); 
     }); 
 } 
 mysql(function(client){ 
     client.query( 
         'SELECT * FROM sample_table',, 
         function(err,res,fields){ 
             console.log(res); 
             client.end(); 
         } 
     ); 
 }); 

としたが、以下のようなエラーが出る。

$ node server.js 

node.js:134
        throw e; // process.nextTick error, or 'error' event on first tick
        ^
Error: deprecated: connect() is now done automatically.

【原因】

サーバの作り方が古かったようだ。まさにこれ。

error connecting to MySQL database

【解決】

server.js全文

var client = require('mysql').createClient({
    'host'        : 'sampleHost', 
    'database'  : 'sampleDatabase', 
    'user'         : 'sampleUser', 
    'password' : 'samplePassword', 
}); 
 
client.query( 
    'SELECT * FROM events',, 
    function(err,res,fields){ 
        console.log(res); 
    } 
); 

からの

$ node server.js

すると、console上で

[ { id: 1,
    title: 'testEvent01',
    created_by: 'otiai10',
    date_from: Mon, 16 Jul 2012 00:56:18 GMT,
    date_to: Mon, 16 Jul 2012 00ã¦ã­', GMT,
    ctime: Mon, 16 Jul 2012 00:56:18 GMT },
  { id: 2,
    title: 'testEvent02',
    created_by: 'otiai10',
    date_from: Mon, 16 Jul 2012 00:57:00 GMT,
    date_to: Mon, 16 Jul 2012 0ãŸã‚‰ï¼Ÿ',T,
    ctime: Mon, 16 Jul 2012 00:57:00 GMT },
  { id: 3,
    title: 'testEvent03',
    created_by: 'otiai10',
    date_from: Mon, 16 Jul 2012 00:57:18 GMT,
    date_to: Mon, 16 Jul 2012 00:57:18 GMT,
    ctime: Mon, 16 Jul 2012 00:57:58 GMT } ]

で、イケてるみたいだ。

【雑感】

ドキュメントを読むとか、公式コミュニティのやりとりを読むとか、慣れてきた