国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

Node連接mysql數(shù)據(jù)庫方法介紹

2019-11-19 17:42:16
字體:
供稿:網(wǎng)友

使用Node做Web開發(fā),基本上都是使用NoSQL數(shù)據(jù)庫,最頻繁的就是使用MongoDB了,自己做了一些簡(jiǎn)單的Web開發(fā),為了降低學(xué)習(xí)門檻,一直使用MySQL來做數(shù)據(jù)庫。這里簡(jiǎn)單介紹一下連接MySQL數(shù)據(jù)庫的方式,希望能幫助到其他人。

npm install --save mysql

使用上述命令安裝完MySQL的模塊后,就可以直接使用了,官網(wǎng)的DOCS里一個(gè)簡(jiǎn)單的例子如下就可以入門了。

var mysql = require('mysql');var connection = mysql.createConnection({ host: 'localhost', user: 'me', password : 'secret', database : 'my_db'});connection.connect();connection.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if (err) throw err; console.log('The solution is: ', rows[0].solution);});connection.end();

很簡(jiǎn)單的一個(gè)例子,從上面的例子可以得出:使用createConnection(option)方法創(chuàng)建一個(gè)連接對(duì)象,然后連接對(duì)象的connect()方法創(chuàng)建連接,最后使用query()方法執(zhí)行SQL語句,返回結(jié)果作為回調(diào)函數(shù)的參數(shù)rows返回,rows為數(shù)組類型。

1. 連接

創(chuàng)建連接對(duì)象,需要傳入連接數(shù)據(jù)庫的一些連接參數(shù),也就是createConnection(option)里的option,option是一個(gè)對(duì)象,以鍵值對(duì)的形式傳入createConnection()方法里。上例列舉出了最基本的參數(shù):

  • host 主機(jī)名
  • user 連接數(shù)據(jù)庫的用戶
  • password 密碼
  • database 數(shù)據(jù)庫名稱

還有其他的參數(shù),可以查詢下官方DOCS,這里不一一列舉了,初期學(xué)習(xí)上面這些參數(shù)就足以。

2. 關(guān)閉

關(guān)閉一個(gè)連接使用end()方法,end()方法提供一個(gè)回調(diào)函數(shù),如下:

connect.end(function(err){  console.log('End a connection');});

這是建議使用的方法,end()方法會(huì)等待連接回調(diào)完成后才關(guān)閉連接。官方還提供了另外一種方法destroy()方法,這個(gè)方法直接關(guān)閉連接,不會(huì)等待回調(diào)完成。

舉個(gè)簡(jiǎn)單的例子:

var mysql = require('mysql');var option = require('./connect.js').option;var conn = mysql.createConnection(option);conn.query('select * from message',function(err,rows,fields){ if(!err){  console.log(rows); }});conn.end(function(err){ console.log('end a connection');});

最終結(jié)果會(huì)是:先打印完SELECT數(shù)據(jù)表結(jié)果后,再打印end a connection。而如果你將關(guān)閉方法換成conn.destroy();,那么你就別想返回任何結(jié)果了,因?yàn)檫€沒等回調(diào)結(jié)束就已經(jīng)終止連接了。

3. 連接池

連接池的原理是一開始就給你創(chuàng)建多個(gè)連接對(duì)象放在一個(gè)“池子”里,用的時(shí)候取一個(gè),用完了放回“池子”里,在一定程度上是有利于節(jié)省系統(tǒng)開銷的,因?yàn)檫B接對(duì)象是在最開始的時(shí)候就創(chuàng)建好了,使用的時(shí)候不再需要系統(tǒng)開銷去創(chuàng)建數(shù)據(jù)庫連接對(duì)象。官方DOCS介紹了連接方法:

var mysql = require('mysql');var pool = mysql.createPool({ connectionLimit : 10, host      : 'example.org', user      : 'bob', password    : 'secret', database    : 'my_db'});pool.query('SELECT 1 + 1 AS solution', function(err, rows, fields) { if (err) throw err; console.log('The solution is: ', rows[0].solution);});

創(chuàng)建連接池的方法是createPool(option),option里多了一個(gè)參數(shù)connectionLimit指的是一次性在連接池里創(chuàng)建多少個(gè)連接對(duì)象,默認(rèn)10個(gè)。如果你想共享一個(gè)連接對(duì)象,可以使用下面方法進(jìn)行連接;

var mysql = require('mysql');var pool = mysql.createPool({ host   : 'example.org', user   : 'bob', password : 'secret', database : 'my_db'});pool.getConnection(function(err, connection) { // Use the connection connection.query( 'SELECT something FROM sometable', function(err, rows) {  // And done with the connection.  connection.release();  // Don't use the connection here, it has been returned to the pool. });// Use the connection connection.query( 'SELECT something2 FROM sometable2', function(err, rows) {  // And done with the connection.  connection.release();  // Don't use the connection here, it has been returned to the pool. });});

使用一個(gè)連接對(duì)象執(zhí)行兩次query()函數(shù)。

4. 示例1

使用基本的連接方式來連接數(shù)據(jù)庫,分別定義數(shù)據(jù)連接以及關(guān)閉的function,如下示例:

// connect.js 數(shù)據(jù)庫連接與關(guān)閉var mysql = require('mysql');var config = require('./config.json'); // 將數(shù)據(jù)庫連接參數(shù)寫入mysql對(duì)象,即config.mysqlvar connCount = 0; // 統(tǒng)計(jì)目前未關(guān)閉的連接exports.getConn = function(){ connCount ++; console.log('............................OPEN a connection, has '+ connCount + ' connection.'); return mysql.createConnection(config.mysql);};exports.endConn = function(conn){ conn.end(function(err){  if(!err){   connCount --;   console.log('.........................CLOSE a connection, has '+ connCount + ' connection.');  } });};

然后給個(gè)使用數(shù)據(jù)庫的示例,

// db.js 查詢用戶信息var connect = require('./connect.js'); // 引入數(shù)據(jù)連接方法exports.getUser = function(username, callback){  var connection = connect.getConn();  var sql = 'select * from user where username = "' + username + '"';  connection.query(sql,function(err,rows,fields){    callback(err,rows,fields);    });  connect.endConn(connection);}

5. 示例2

使用數(shù)據(jù)庫連接池,同樣先創(chuàng)建數(shù)據(jù)庫連接池的方法,如下兩種方式:

// connect.js 直接使用var mysql = require('mysql');var config = require('./config.json');var pool = mysql.createPool(config.mysql);exports.querySQL = function(sql,callback){  pool.query(sql, function(err,rows,fields){    callback(err,rows,fields);  });}
// connect.js 使用getConnection方法var mysql = require('mysql');var config = require('./config.json');var pool = mysql.createPool(config.mysql);exports.querySQL = function(sql, callback){  pool.getConnection(function(err,conn){    conn.query(sql,function(err,rows,fields){      callback(err,rows,fields);       conn.release();  // 不要忘了釋放    });      });}

使用的時(shí)候,直接使用querySQL方法即可,如下:

// db.js 查詢用戶信息var connect = require('./connect.js');exports.getUser = function(username,callback){  var sql = 'select * from user where username = "' + username + '"';  connect.querySQL(sql,function(err,rows,fields){    callback(err,rows,fields);      });};

官方是推薦使用連接池的方式進(jìn)行連接的,但是,是直接使用pool.query()連接還是pool.getConnection()的方法來連接,官方并沒有介紹其優(yōu)劣,我簡(jiǎn)單做了個(gè)測(cè)試,貌似這兩種方式并沒有多大的區(qū)別,也就沒再研究,有知道的煩請(qǐng)告知,謝了~

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持武林網(wǎng)。

發(fā)表評(píng)論 共有條評(píng)論
用戶名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 济阳县| 紫阳县| 荥阳市| 元氏县| 阳高县| 南雄市| 拜城县| 定西市| 娄底市| 美姑县| 从江县| 蒙自县| 河池市| 惠州市| 昆明市| 鄂尔多斯市| 手游| 舒兰市| 临泽县| 吉安市| 曲松县| 衢州市| 岗巴县| 屏东县| 大洼县| 武宁县| 新邵县| 松潘县| 绿春县| 信丰县| 南皮县| 溧阳市| 济阳县| 托里县| 独山县| 彭泽县| 青岛市| 晋江市| 衡阳县| 晴隆县| 宜良县|