通过 WebService 提供 SQL XML(SQL 2005)






4.39/5 (9投票s)
如何通过 WebService 提供 SQL 2005 中的 XML
引言
我最近需要为客户创建来自 SQL Server 中保存的一些数据的馈送,所以我寻找了最佳(也是最快)的方式来做到这一点。 我知道我使用 SQL 2005 并且 XML 是其不可或缺的一部分,所以我研究了利用它的方法。
经过一番思考,我想出了一个主意,即从数据库提供 XML,并创建一个 WebService
,客户可以在需要一些数据时调用它(如果需要,可以使用一些参数)。
现在,我知道你们都在说“这没什么新鲜或困难的”,这正是写这篇文章的意义所在。 它很容易,因此很容易被忽视。 我简直不敢相信它如此简单,而且似乎 CodeProject 上没有任何其他文章告诉任何人如何解决这个问题。
Using the Code
首先,使用您的 SQL 2005 数据库(其中已经有一些数据),创建一个如下所示的存储过程
CREATE PROCEDURE [dbo].[GetStories]
@fromDate datetime,
@toDate datetime
AS
BEGIN
select dbo.Story.id,
description,
notes,
text,
publicationdate,
authorsnames,
keywords
from dbo.Story
inner join dbo.Status on dbo.Story.StatusId = dbo.Status.id
where publicationdate between @fromDate and @toDate
and dbo.Status.status = 'live'
order by publicationDate
FOR XML PATH('story'),
ROOT('stories')
END
此步骤的关键是 FOR XML PATH(###), ROOT(###)
部分。 这告诉 SQL Server 返回 XML,其中每行都具有元素名称 story
,并且 XML 文档的根为 stories
。
接下来,使用常用的项目选项创建一个普通的 WebService
,并添加一个新的 WebMethod
。 在此方法中,连接到数据库并获取数据。
现在,由于我想要返回 XML,因此我调用 SqlCommand
类上的 ExecuteXmlReader
方法,如下所示
XmlReader reader = command.Command.ExecuteXmlReader();
然后可以将此读取器流式传输到 XmlDataDocument
中,然后可以从 WebMethod
返回。 下面是我的 WebMethod
副本,您会注意到一个简单的 Database
类和 App_Data.SqlSPCommand
,以简化对数据库的调用
[WebMethod(Description = "Get stories based on a centre, and a from and to date",
CacheDuration = 600, MessageName = "GetStoriesForCentre")]
public XmlDataDocument GetStoriesForCentre
(string centre, DateTime fromDate, DateTime toDate)
{
Database db = new Database("TarkStoriesConnectionString");
using (db.Connection)
{
db.OpenConnection();
App_Data.SqlSPCommand command = new App_Data.SqlSPCommand
("GetStoriesForCentre", db.Connection);
command.AddParameter("@centre", SqlDbType.VarChar, centre);
command.AddParameter("@fromDate", SqlDbType.DateTime, fromDate);
command.AddParameter("@toDate", SqlDbType.DateTime, toDate);
XmlReader reader = command.Command.ExecuteXmlReader();
XmlDataDocument xml = new XmlDataDocument();
xml.Load(reader);
return xml;
}
}
就是这样!
以正常方式调用 WebService
,提供一些查询字符串参数(在我的示例中是 2 个日期),您应该会得到一些如下所示的 XML 返回
<?xml version="1.0" encoding="utf-8" ?>
<stories>
<story>
<id>514</id>
<description>some description</description>
<notes>no notes available</notes>
<text>blah blah blah</text>
<publicationdate>2007-01-30T00:00:00</publicationdate>
<authorsnames>Sue Williams</authorsnames>
<keywords>boring story</keywords>
</story>
</stories>
您可能希望首先检查是否有任何内容(使用 MoveToContent
并检查结果)来整理将 XmlReader
加载到 XmlDataDocument
类中的过程,但现在我将其留给你们所有人。
关注点
这太简单了,希望我可以帮助那些可能被忽视的人指出显而易见的事情。
历史
- 2007 年 2 月 4 日:初始发布