nodejs mysql 數據查詢例子

1、安裝nodejs

2、安裝mysql npm包

地址:https://github.com/felixge/node-mysql

npm install mysql
3、相應API查看及調用:

var mysql = require(‘mysql’);
var connection = mysql.createConnection({
host : ‘localhost’,
user : ‘me’,
password : ‘secret’
});

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();
4、相關注意點及方法

將相應結果進行文件形式保存,使用fs文件系統及path路徑模塊

var $ = require(‘underscore’);
var fs = require(‘fs’);
var path = require(‘path’);
underscore爲數據處理集合,可以簡單快捷的進行數據的遍歷拼接等處理

npm install underscore
connection.query(‘select * from xmmember’, function (err, rows) {//account 用戶賬戶表
if (err) throw err;
var tempAccount = $.map(rows, function (c) {
return {
id: c.ID,
name: c.m_username,
password: c.m_userpass,
surePassword: c.m_userpass,
qq: c.qq
}
});
fs.writeFile(path.join(__dirname, ‘account.js’), JSON.stringify(tempAccount), function (err) {
if (err) throw err;
console.log(“Export Account Success!”);
});
});
將數據查詢結果進行JSON格式轉換後,導出到具體文件中,方便相應的系統進行導入等管理操作。

相關API方法:

1、配置query格式,進行相應update的操作,代碼如下:

connection.config.queryFormat = function (query, values) {
if (!values) return query;
return query.replace(/:(\w+)/g, function (txt, key) {
if (values.hasOwnProperty(key)) {
return this.escape(values[key]);
}
return txt;
}.bind(this));
};

connection.query(“UPDATE posts SET title = :title”, { title: “Hello MySQL” });
2、執行insert操作。如下:

connection.query(‘INSERT INTO posts SET ?’, {title: ‘test’}, function(err, result) {
if (err) throw err;

console.log(result.insertId);
});
3、刪除delete的執行,示例代碼以下:

connection.query(‘DELETE FROM posts WHERE title = “wrong”’, function (err, result) {
if (err) throw err;

console.log(‘deleted ’ + result.affectedRows + ’ rows’);
})
4、大量數據查詢及操作時候,可以加入相應的容錯處理:示例代碼如下:

var query = connection.query(‘SELECT * FROM posts’);
query
.on(‘error’, function(err) {
// Handle error, an ‘end’ event will be emitted after this as well
})
.on(‘fields’, function(fields) {
// the field packets for the rows to follow
})
.on(‘result’, function(row) {
// Pausing the connnection is useful if your processing involves I/O
connection.pause();

processRow(row, function() {
  connection.resume();
});

})
.on(‘end’, function() {
// all rows have been received
});
其中,err爲具體出現錯誤時候,所需要進行的錯誤處理。

fields爲具體的執行的結果集合

row爲具體結果集每行的處理,可暫停執行及恢復執行。

5、多個查詢的同時執行處理,示例代碼如下:

先進行如下配置:

var connection = mysql.createConnection({multipleStatements: true});
即可進行多個語句的執行,寫法如下:

connection.query(‘SELECT 1; SELECT 2’, function(err, results) {
if (err) throw err;

// results is an array with one element for every statement in the query:
console.log(results[0]); // [{1: 1}]
console.log(results[1]); // [{2: 2}]
});
6、結果進行組裝處理,代碼如下:

var options = {sql: ‘…’, nestTables: true};
connection.query(options, function(err, results) {
/* results will be an array like this now:
[{
table1: {
fieldA: ‘…’,
fieldB: ‘…’,
},
table2: {
fieldA: ‘…’,
fieldB: ‘…’,
},
}, …]
*/
});
或使用如下方式:

var options = {sql: ‘…’, nestTables: ‘_’};
connection.query(options, function(err, results) {
/* results will be an array like this now:
[{
table1_fieldA: ‘…’,
table1_fieldB: ‘…’,
table2_fieldA: ‘…’,
table2_fieldB: ‘…’,
}, …]
*/
});
7、事物的執行及處理。代碼如下:

connection.beginTransaction(function(err) {
if (err) { throw err; }
connection.query(‘INSERT INTO posts SET title=?’, title, function(err, result) {
if (err) {
connection.rollback(function() {
throw err;
});
}

var log = 'Post ' + result.insertId + ' added';

connection.query('INSERT INTO log SET data=?', log, function(err, result) {
  if (err) { 
    connection.rollback(function() {
      throw err;
    });
  }  
  connection.commit(function(err) {
    if (err) { 
      connection.rollback(function() {
        throw err;
      });
    }
    console.log('success!');
  });
});

});
});
beginTransaction(), commit() and rollback() 三個方法分別針對SQL事物的開始執行,提交,回滾三個操作。

8、執行超時的捕捉處理,示例代碼如下:

connection.query({sql: ‘SELECT COUNT(*) AS count FROM big_table’, timeout: 60000}, function (err, rows) {
if (err && err.code === ‘PROTOCOL_SEQUENCE_TIMEOUT’) {
throw new Error(‘too long to count table rows!’);
}

if (err) {
throw err;
}

console.log(rows[0].count + ’ rows’);
});
9、同時可以對SQL錯誤代碼的處理,示例代碼如下:

var connection = require(‘mysql’).createConnection({
port: 84943, // WRONG PORT
});

connection.connect(function(err) {
console.log(err.code); // ‘ECONNREFUSED’
console.log(err.fatal); // true
});

connection.query(‘SELECT 1’, function(err) {
console.log(err.code); // ‘ECONNREFUSED’
console.log(err.fatal); // true
});
最後,node mySQL提供強大的數據池羣處理,以及SSL加密驗證功能,在此不做說明,可查看具體API。

發佈了33 篇原創文章 · 獲贊 8 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章