安裝依賴庫node
npm install mysql
建立數據庫鏈接mysql
var mysql = require('mysql'); //定義鏈接參數 var mysqlConn = { host:'127.0.0.1', user:'user', password:'password', database:'nodejs', port:'3306' }; //建立鏈接 var conn = mysql.createConnection(mysqlConn); conn.connect(); //執行sql conn.query('select 1+1 as solution ',function(err,rows,fields){ if (err) {throw err;} console.log('select result is '+ rows[0].so); }) //關閉鏈接? conn.end();
使用數據庫鏈接池sql
var mysql = require('mysql'); var mysqlConn = { host:'127.0.0.1', user:'root', password:'jt123456', database:'nodejs', port:'3306' }; var pool = mysql.createPool(mysqlConn); // 從鏈接池獲取connection pool.getConnection(function(err,conn){ if (err) { console.log('err when getConnection from pool:'+err); } conn.query('select 1+1 as solution',function(err,rows){ if (err) { consloe.log('err when query sql :'+err); } console.log('solution is '+rows[0].solution); // 釋放當前connection conn.release(); }); });
處理鏈接時的異常數據庫
var mysql = require('mysql'); var mysqlConn = { host:'127.0.0.1', user:'root', password:'jt123456', database:'nodejs', port:'3306' }; // 重連 function handleError(){ var conn = mysql.createConnection(mysqlConn); //鏈接時發生異常就打印錯誤並在2秒後重連 conn.connect(function(err){ if (err) { console.log('err when connect with mysql server:'+err); }; setTimeout(handleError,2000); }); //監聽鏈接中的異常 conn.on('error',function(err){ console.log('err:'+err); //斷開鏈接時自動重連 if (err.code ==='PROTOCOL_CONNECTION_LOST') { handleError(); }else{ throw err; } }); } handleEror();
參考資料:用Nodejs鏈接MySQLnpm