node.js结合edge连接sqlserver数据库读取数据并显示

原文:http://tech.pro/tutorial/1852/how-to-leverage-sql-server-with-nodejs-using-edgejs(How to leverage SQL Server with Node.js using Edge.js)

注意连接字符串的处理,文章中这样说道:

Configure your connection string

Before you can use Edge.js with SQL Server, you must set an environment variable named EDGE_SQL_CONNECTION_STRING to a valid ADO.NET connection string. For example:

> set EDGE_SQL_CONNECTION_STRING=Data Source=localhost;Initial Catalog=node-test;Integrated Security=True

EDGE_SQL_CONNECTION_STRING是全局环境变量,用于指定连接的数据库字符串

Further reading

  • Edge.js Readme
  • Edge.js is 32x faster than a cross-process call
  • Introducing Node.js Tools for Visual Studio
  • Access SQL Azure from a Node.js app...

按照上面文章描述,我们建立一个数据库node-test,然后执行sql语句:

IF EXISTS(SELECT 1 FROM sys.tables WHERE object_id = OBJECT_ID('SampleUsers'))
BEGIN;
    DROP TABLE SampleUsers;
END;
GO

CREATE TABLE SampleUsers (
    Id INTEGER NOT NULL IDENTITY(1, 1),
    FirstName VARCHAR(255) NOT NULL,
    LastName VARCHAR(255) NOT NULL,
    Email VARCHAR(255) NOT NULL,
    CreateDate  VARCHAR(20)--DATETIME NOT NULL DEFAULT(getdate()),
    PRIMARY KEY (Id)
);
GO

INSERT INTO SampleUsers(FirstName,LastName,Email,CreateDate) VALUES('Orla','Sweeney','[email protected]','Apr 13, 2013');
INSERT INTO SampleUsers(FirstName,LastName,Email,CreateDate) VALUES('Zia','Pickett','[email protected]','Aug 31, 2013');
INSERT INTO SampleUsers(FirstName,LastName,Email,CreateDate) VALUES('Justina','Ayala','[email protected]','Jul 28, 2013');
INSERT INTO SampleUsers(FirstName,LastName,Email,CreateDate) VALUES('Levi','Parrish','[email protected]','Jun 21, 2013');
INSERT INTO SampleUsers(FirstName,LastName,Email,CreateDate) VALUES('Pearl','Warren','[email protected]','Mar 3, 2013');
INSERT INTO SampleUsers(FirstName,LastName,Email,CreateDate) VALUES('Rinah','Compton','[email protected]','Oct 24, 2013');
INSERT INTO SampleUsers(FirstName,LastName,Email,CreateDate) VALUES('Hasad','Shepherd','[email protected]','Sep 15, 2013');
INSERT INTO SampleUsers(FirstName,LastName,Email,CreateDate) VALUES('Noelani','Hill','[email protected]','Jun 6, 2013');
INSERT INTO SampleUsers(FirstName,LastName,Email,CreateDate) VALUES('Nicole','Jacobson','[email protected]','Aug 8, 2013');
INSERT INTO SampleUsers(FirstName,LastName,Email,CreateDate) VALUES('Alika','Acosta','[email protected]','Nov 23, 2013');

select * from SampleUsers
node.js结合edge连接sqlserver数据库读取数据并显示_第1张图片
编写node.js脚本:

var http = require('http');
var edge = require('edge');
var port = process.env.PORT || 8080;

var getTopUsers = edge.func('sql', function () {/*
    SELECT TOP 5 * FROM SampleUsers ORDER BY CreateDate DESC
*/});

function logError(err, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.write("Error: " + err);
    res.end("");
}

http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/html' });

    getTopUsers(null, function (error, result) {
        if (error) { logError(error, res); return; }
        if (result) {
            res.write("<ul>");
            result.forEach(function(user) {
                res.write("<li>" + user.FirstName + " " + user.LastName + ": " + user.Email + "</li>");
            });
            res.end("</ul>");
        }
        else {
            res.end("No results");
        }
    });
}).listen(port);
console.log("Node server listening on port " + port);
保存为server-sql-query.js(注意,它使用了edge)
打开dos,指定数据库连接字符串,文章中说明有两种写法的(set和SETX【它要大写的】),随便用一个,我用的是set语句:

set EDGE_SQL_CONNECTION_STRING=Data Source=localhost;Initial Catalog=node-test;uid=sa;pwd=Jon123;
然后node命令运行刚刚新建的server-sql-query.js

成功运行便会打印出“node服务器正在监听8080端口”的信息
然后我们在浏览器中输入 http://localhost:8080地址便会显示如下结果:

node.js结合edge连接sqlserver数据库读取数据并显示_第2张图片

到此结束。

ps:文章中靠近结尾处,作者的指出的一些看法挺好的,一并摘录此处留着研究

Final thoughts

Edge.js appears to be a very promising solution to bridge the gap between Node.js and the world of .NET.

  • Although .NET code can be executed in-line, I highly recommend managing all .NET code in a separate assembly.
  • An ORM can make your life much easier. I prefer Micro-ORMs that aren't heavy-handed and let me do my own thing. Unfortunately, not many ORMs have adopted async support. AsyncPoco and Insight.Database look promising, but I have not tried them.
  • If you use Visual Studio, download and install the Node.js Tools for Visual Studio.
  • Remember, stay async in .NET as much as possible!
  • Test, test, test! Profile your application's memory, CPU, and concurrency under load to ensure something isn't going terribly wrong between Node.js and .NET.
  • If your motivation for using Node.js is concurrency and scalability, or reducing your Microsoft licensing footprint, you may want to consider benchmarking Edge.js against a message queue architecture. Take a look at using RabbitMQ or ZeroMQbetween your Node.js and Windows environments. A message-based architecture has many benefits. Use the solution that works best for you.
  • Your mileage may vary.
  • Just because you can, doesn't mean you should.
  • Consume copious amounts of caffeine and bacon.
其中说道基于edge.js的消息队列2个项目,挺好的。

你可能感兴趣的:(nodejs,nodejs连接数据库)