最近研究Nodejs,连接SQLSERVER挺麻烦,资料也很少,我就发点福利,走过路过,随便瞧瞧。
首先说一下环境细节,Nodejs环境不多说了,网上资料很多,主要说说msnodesql这个模块。安装命令 npm install msnodesql -g ,由于这个驱动是C/C++编写的,需要编译环境,大体就是以下:
The following prerequisites are necessary prior to using the driver:
Node.js - use the latest version if possible, but it has been tested on node 0.6.10 and later
node-gyp - latest version installed globally (npm install -g node-gyp)
python 2.7.x - for node-gyp (make sure it is in the path)
Visual C++ 2010 - the Express edition is freely available from Microsoft
SQL Server Native Client 11.0 - available as Microsoft SQL Server 2012 Native Client found in the SQL Server 2012 Feature Pack
编译命令:
Build
第一步:到msnodesql文件夹路径
node-gyp configure
第二步:还是在此文件夹下执行
node-gyp build
(Or to build the debug version:node-gyp build --debug)
最后生成sqlserver.node,这个文件十分重要,然后将对应的node_modules\msnodesql\build\Release文件夹下其他文件全部删掉,只留sqlserver.node文件及对应的路径文件夹,
如果感觉以上操作很苦逼,那也没关系,告诉一个一步登天的窍门,直接去网上下载编译好sqlserver.node,放到你的项目对应的node_modules\msnodesql\build\Release文件夹里,就可以直接操作sqlserver了。
以下是服务器端代码,可以通过node命令执行,为了方便快速,我省略了routes路由这一步:
var express = require('express'); var path = require('path'); var favicon = require('static-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var ejs = require('ejs'); //定义加载的项目模块 var util = require('util'); var app = express(); app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'ejs'); app.use(express.static(path.join(__dirname, 'public'))); var sql = require('msnodesql'); var conn_str = "Driver={SQL Server Native Client 11.0};Server={.};Database={DB_ESHOP};Trusted_Connection={Yes}"; app.get('/', function (req, res) { var pageindex = req.query.page || 1, jsonObj = {}, jaonarray = [], pagesize = 10, fysql = "SELECT TOP 5 * FROM Goods WHERE ID NOT IN ( SELECT TOP (2 *(" + pageindex + "-1)) ID FROM Goods ORDER BY ID) ORDER BY [ID]"; sql.open(conn_str, function (err, conn) { //取得一个表里的列名 // sql.queryRaw(conn_str, "select name from syscolumns Where ID= OBJECT_ID('LoanProducts')", function (err, results) { // if (err) { // console.log(err); // } else { // for (var k = 0; k < results.rows.length; k++) { // jsonObj[results.rows[k][0]]=""; // } // } // console.log(jsonObj); // }); sql.queryRaw(conn_str, fysql, function (err, results) { if (err) { console.log(err); } else { for (var i = 0; i < results.rows.length; i++) { jaonarray.push(results.rows[i]); console.log(jaonarray); } } res.render('json', { layout : "fasles", imp : jaonarray }); }); }); }); var http = require('http'); http.createServer(app).listen(app.get('port'), function () { console.log('Express server listening on port ' + app.get('port')); }); |
以下是服务器端执行效果:
以下是页面效果:
接下来我们看看msnodesql核心脚本sql.js,其实总共就提供了三个方法:
大概就是这样,如果需要深入,自行研究,开源的力量无边无际。。。