Node連接mysql數(shù)據(jù)庫方法介紹
使用Node做Web開發(fā),基本上都是使用NoSQL數(shù)據(jù)庫,最頻繁的就是使用MongoDB了,自己做了一些簡單的Web開發(fā),為了降低學習門檻,一直使用MySQL來做數(shù)據(jù)庫。這里簡單介紹一下連接MySQL數(shù)據(jù)庫的方式,希望能幫助到其他人。
npm install --save mysql
使用上述命令安裝完MySQL的模塊后,就可以直接使用了,官網(wǎng)的DOCS里一個簡單的例子如下就可以入門了。
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();
很簡單的一個例子,從上面的例子可以得出:使用createConnection(option)方法創(chuàng)建一個連接對象,然后連接對象的connect()方法創(chuàng)建連接,最后使用query()方法執(zhí)行SQL語句,返回結果作為回調(diào)函數(shù)的參數(shù)rows返回,rows為數(shù)組類型。
1. 連接
創(chuàng)建連接對象,需要傳入連接數(shù)據(jù)庫的一些連接參數(shù),也就是createConnection(option)里的option,option是一個對象,以鍵值對的形式傳入createConnection()方法里。上例列舉出了最基本的參數(shù):
- host 主機名
- user 連接數(shù)據(jù)庫的用戶
- password 密碼
- database 數(shù)據(jù)庫名稱
還有其他的參數(shù),可以查詢下官方DOCS,這里不一一列舉了,初期學習上面這些參數(shù)就足以。
2. 關閉
關閉一個連接使用end()方法,end()方法提供一個回調(diào)函數(shù),如下:
connect.end(function(err){
console.log('End a connection');
});
這是建議使用的方法,end()方法會等待連接回調(diào)完成后才關閉連接。官方還提供了另外一種方法destroy()方法,這個方法直接關閉連接,不會等待回調(diào)完成。
舉個簡單的例子:
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');
});
最終結果會是:先打印完SELECT數(shù)據(jù)表結果后,再打印end a connection。而如果你將關閉方法換成conn.destroy();,那么你就別想返回任何結果了,因為還沒等回調(diào)結束就已經(jīng)終止連接了。
3. 連接池
連接池的原理是一開始就給你創(chuàng)建多個連接對象放在一個“池子”里,用的時候取一個,用完了放回“池子”里,在一定程度上是有利于節(jié)省系統(tǒng)開銷的,因為連接對象是在最開始的時候就創(chuàng)建好了,使用的時候不再需要系統(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里多了一個參數(shù)connectionLimit指的是一次性在連接池里創(chuàng)建多少個連接對象,默認10個。如果你想共享一個連接對象,可以使用下面方法進行連接;
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.
});
});
使用一個連接對象執(zhí)行兩次query()函數(shù)。
4. 示例1
使用基本的連接方式來連接數(shù)據(jù)庫,分別定義數(shù)據(jù)連接以及關閉的function,如下示例:
// connect.js 數(shù)據(jù)庫連接與關閉
var mysql = require('mysql');
var config = require('./config.json'); // 將數(shù)據(jù)庫連接參數(shù)寫入mysql對象,即config.mysql
var connCount = 0; // 統(tǒng)計目前未關閉的連接
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.');
}
});
};
然后給個使用數(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(); // 不要忘了釋放
});
});
}
使用的時候,直接使用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);
});
};
官方是推薦使用連接池的方式進行連接的,但是,是直接使用pool.query()連接還是pool.getConnection()的方法來連接,官方并沒有介紹其優(yōu)劣,我簡單做了個測試,貌似這兩種方式并沒有多大的區(qū)別,也就沒再研究,有知道的煩請告知,謝了~
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Nest.js參數(shù)校驗和自定義返回數(shù)據(jù)格式詳解
這篇文章主要給大家介紹了關于Nest.js參數(shù)校驗和自定義返回數(shù)據(jù)格式的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-03-03

