nodejs訪問mssql資料庫
阿新 • • 發佈:2019-01-05
var user = "sa",
password = "masterkey",
server = "127.0.0.1",
database = "EMacIntf";
var db={};
var config = {
user: user,
password: password,
server: server,
database: database,
options:{
//encrypt: true
},
pool:{
min: 0,
idleTimeoutMillis: 3000
}
};var restoreDefaults = function(){
config={
user:user,
password:password,
server:server,
database:database,
options:{
//encrypt: true
},
pool:{
min: 0,
idleTimeoutMillis: 3000
}
};
}db.querySql = function(sql, params, callBack){
var connection = new mssql.Connection(config, function(err){
var ps = new mssql.PreparedStatement(connection);
if(params != ""){
for(var index in params){
if(typeof params[index] == "number"){
ps.input(index, mssql.Int);
}else if(typeof params[index] == "string"){
ps.input(index, mssql.NVarChar);
}
}
}
ps.prepare(sql, function(err){
if(err)
console.log(err);
ps.execute(params, function(err, recordset){
callBack(err, recordset);
ps.unprepare(function(err){
if(err)
console.log(err);
});
});
});
});
restoreDefaults();
};module.exports=db;這裡執行查詢語句、增刪改、儲存過程語句都可以,基本上可以完成正常的業務邏輯操作。呼叫範例:var db = require("./db.js");db.querySql("select * from XXX", null, function(err, data){
res.send(JSON.stringify(data));
});
首先下載微軟的mssql支援庫:npm install -g [email protected]
var mssql = require("mssql");var user = "sa",
password = "masterkey",
server = "127.0.0.1",
database = "EMacIntf";
var db={};
var config = {
user: user,
password: password,
server: server,
database: database,
options:{
//encrypt: true
},
pool:{
min: 0,
idleTimeoutMillis: 3000
}
};var restoreDefaults = function(){
config={
user:user,
password:password,
server:server,
database:database,
options:{
//encrypt: true
},
pool:{
min: 0,
idleTimeoutMillis: 3000
}
};
}db.querySql = function(sql, params, callBack){
var connection = new mssql.Connection(config, function(err){
var ps = new mssql.PreparedStatement(connection);
if(params != ""){
for(var index in params){
if(typeof params[index] == "number"){
ps.input(index, mssql.Int);
}else if(typeof params[index] == "string"){
ps.input(index, mssql.NVarChar);
}
}
}
ps.prepare(sql, function(err){
if(err)
console.log(err);
ps.execute(params, function(err, recordset){
callBack(err, recordset);
ps.unprepare(function(err){
if(err)
console.log(err);
});
});
});
});
restoreDefaults();
};module.exports=db;這裡執行查詢語句、增刪改、儲存過程語句都可以,基本上可以完成正常的業務邏輯操作。呼叫範例:var db = require("./db.js");db.querySql("select * from XXX", null, function(err, data){
res.send(JSON.stringify(data));
});