1、使用MSsql微软官方npm包,支持不够强大
npm install mssql@3.3.0 使用3X的版本4X的升级了 下面的用不了了。
下面是一个封装,复制至:
var mssql = require('mssql');
var user = "sa",
password = "123456",
server = "127.0.0.1",
database = "test";
var config = {
user: user,
password: password,
server: server, // You can use 'localhost\\instance' to connect to named instance
database: database,
options: {
encrypt: true // Use this if you're on Windows Azure
},
pool: {
min: 0,
idleTimeoutMillis: 3000
}
};
var initConfig = function (user, password, server, database) {
config = {
user: user,
password: password,
server: server, // You can use 'localhost\\instance' to connect to named instance
database: database,
options: {
encrypt: true // Use this if you're on Windows Azure
},
pool: {
min: 0,
idleTimeoutMillis: 3000
}
}
};
var restoreDefaults = function () {
config = {
user: user,
password: password,
server: server, // You can use 'localhost\\instance' to connect to named instance
database: database,
options: {
encrypt: true // Use this if you're on Windows Azure
},
pool: {
min: 0,
idleTimeoutMillis: 3000
}
};
};
var 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();
};
//querySql("select id as roleId,roleName from dbo.role","",function(err,recordset){
// console.dir(recordset);
//});
View Code
下面为其他使用方式,复制:
配置Config
复制代码
const config = {
user: '...',
password: '...',
server: 'localhost',
database: '...',
options: {
encrypt: true //使用windows azure,需要设置次配置。
}
}
复制代码
user:SQL Server 的登录名
password: SQL Server的登录密码
server:SQL Server的地址
port:端口号,默认为1433
domain:设置domain后,可通过domain连接数据库
database:数据库名称
connectionTimeout:连接timeout,单位ms 默认 15000
requestTimeout:请求timeout,单位ms默认15000
parseJSON:将json数据集转化成json obj
pool.max:连接池最大连接数,默认10
pool.min:连接池最小连接数,默认0
pool.idleTimeoutMillis:设置关闭未使用连接的时间,单位ms默认30000
快速开始
复制代码
const sql = require('mssql') //声明插件
sql.connect(config).then(() => {
return sql.query`select * from mytable where id = ${value}`
}).then(result => {
//请求成功
}).catch(err => {
//err 处理
})
sql.on('error', err => {
//error 处理
})
复制代码
Streaming流
如果表格查询的数据量过大,使用Streaming流可以很好地将数据展示出来。
复制代码
const sql = require('mssql')
sql.connect(config, err => {
const request = new sql.Request()
request.stream = true //开启streaming
request.query('select * from verylargetable') //或者执行request.execute(procedure)
request.on('recordset', columns => {
//每次查询会触发一次 recordset事件,返回结果集
})
request.on('row', row => {
//每个结果集会出发row事件,返回row信息
})
request.on('error', err => {
//监听error事件,可能被触发多次
})
request.on('done', result => {
//最后触发
})
})
sql.on('error', err => {
//error 处理
})
复制代码
POOL连接池
数据库连接是非常占用资源的,尤其是在高并发的情况下,如果每次都去建立数据库连接就会有性能问题,也会影响一个应用程序的延展性,
针对这个问题,连接池出现了,连接池就是为了解决这个问题的。
new sql.ConnectionPool(config).connect().then(pool => {
return pool.query`select * from mytable where id = ${value}`
}).then(result => {
console.dir(result)
}).catch(err => {
})
pool.close()非常重要,只创建,不关闭会造成非常严重的内存泄漏。
创建请求及取消请求
复制代码
//创建请求:
const request = new sql.Request(/* [pool 或 transaction] */)
//取消请求:
const request = new sql.Request()
request.query('waitfor delay \'00:00:05\'; select 1 as number', (err, result) => {
})
request.cancel() //取消之前所有的query动作
复制代码
Bulk创建Table
复制代码
const table = new sql.Table('table_name')
table.create = true
table.columns.add('a', sql.Int, {nullable: true, primary: true})
table.columns.add('b', sql.VarChar(50), {nullable: false})
table.rows.add(777, 'test')//添加一行信息
const request = new sql.Request()
request.bulk(table, (err, result) => {
})
复制代码
Execute
执行进程
const request = new sql.Request()
request.input('input_parameter', sql.Int, value)
request.output('output_parameter', sql.Int)
request.execute('procedure_name', (err, result) => {
})
Input(name,type,value)给request添加一个因数
Output(name,type,(value)) 将request返回值,放入name中
Transaction
保证全部的query request在一个连接中完成。Begin创建连接,commit(完成)或者rollback(回滚)释放连接。
复制代码
const transaction = new sql.Transaction(/* [pool] */)
transaction.begin(err => {
const request = new sql.Request(transaction)
request.query('insert into mytable (mycolumn) values (12345)', (err, result) => {
transaction.commit(err => {
console.log("Transaction committed.")
})
})
})
复制代码
Prepared Statement
与transaction很像,但是此处确保全部的procedure在一个连接中执行。Prepare创建连接,unpare释放连接。
复制代码
const ps = new sql.PreparedStatement(/* [pool] */)
ps.input('param', sql.Int)
ps.prepare('select @param as value', err => {
ps.execute({param: 12345}, (err, result) => {
ps.unprepare(err => {
})
})
})
复制代码
CLI
2.0版本后,mssql便支持CLI功能
安装方法:npm install mssql -g ,需要安装至全局
编辑config文件,命名为.mssql.json
执行
echo "select * from mytable" | mssql /path/to/config
//便可打印出查询信息
View Code
2、使用Edge npm 包,好处够强大,C#有多强大,他就有多强大。弊端:不能跨平台。如要跨平台的等mono的支持吧,具体我也没有太关注这个东西。
下面为实现
var edge = require('edge');
var sqlPath = "Data Source=127.0.0.1;Initial Catalog=test;Persist Security Info=True;User ID=sa;Password=123456;Connect Timeout=180;Pooling=False";
var helloWorld = edge.func(function () {/*
async (input) => {
string str = "2017-12-12 12:12:12";
return str.Substring(0, 7);
}
*/});
helloWorld('JavaScript', function (error, result) {
if (error) throw error;
console.log(result);
});
//var edge = require('edge');
var getInsuranceChannelType = edge.func('sql', {
source: function () {/*
select top 2 * from [InsuranceChannelType]
*/},
connectionString: sqlPath
});
getInsuranceChannelType(null, function (error, result) {
if (error) throw error;
console.log(result);
//console.log(result[0].ProductName);
//console.log(result[1].ReorderLevel);
});
/*exports.findById = function (req, res, next) {
getEmployeeById({ Id: req.params.id }, function (error, data) {
if (error) {
console.log(error);
res.send(error.message);
}
if (data) {
res.send(data);
}
else {
var noData = [];
res.send(noData);
}
});
}*/
var getTop10Products = edge.func('sql', {
source: function () {/*
select top 1 * from [InsuranceCompany]
*/
},
connectionString: sqlPath
});
getTop10Products(null, function (error, result) {
if (error) throw error;
console.log(result);
//console.log(result[0].ProductName);
// console.log(result[1].ReorderLevel);
View Code