溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Node中怎么連接mysql數(shù)據(jù)庫

發(fā)布時(shí)間:2021-07-20 16:39:22 來源:億速云 閱讀:274 作者:Leah 欄目:web開發(fā)

Node中怎么連接mysql數(shù)據(jù)庫,很多新手對此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

npm install --save mysql

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

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();

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

1. 連接

創(chuàng)建連接對象,需要傳入連接數(shù)據(jù)庫的一些連接參數(shù),也就是createConnection(option)里的option,option是一個(gè)對象,以鍵值對的形式傳入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è)簡單的例子:

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è)連接對象放在一個(gè)“池子”里,用的時(shí)候取一個(gè),用完了放回“池子”里,在一定程度上是有利于節(jié)省系統(tǒng)開銷的,因?yàn)檫B接對象是在最開始的時(shí)候就創(chuàng)建好了,使用的時(shí)候不再需要系統(tǒng)開銷去創(chuàng)建數(shù)據(jù)庫連接對象。官方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è)連接對象,默認(rèn)10個(gè)。如果你想共享一個(gè)連接對象,可以使用下面方法進(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è)連接對象執(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對象,即config.mysql
var 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);    
  });
};

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI