65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 XML 访问数据库,无需 SQL-XML

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.33/5 (3投票s)

2002 年 4 月 26 日

2分钟阅读

viewsIcon

76433

downloadIcon

1072

如何使用 XML 访问 RDBMS,例如 MS SQL 或 Oracle。核心部分使用了 COM 技术和 ATL。

引言

我设计了一个使用 n 层架构和 XML 的程序,运行在 Windows 2000/ME 下。 表示层是用户界面,可以根据用户的需求进行变化。 主要业务规则放在业务逻辑层中。 并且一些业务逻辑是使用存储在 SQL 或 Oracle 中的存储过程编写的。 我决定使用 XML 在整个系统中传输数据。

它是如何工作的?

当您想执行存储在 Oracle 或 Microsoft SQL Server 中的存储过程或存储函数时,将 XML 片段作为参数发送到 COM 接口。 首先,COM 接口解释命令是什么及其参数,以创建 ADO command 对象。 然后执行该命令。 命令执行后,将返回的记录集和输出参数转换为 XML。 当您获得 XML 时,您可以根据需要处理它。

例如,在数据库中,有一个名为 reptq1 的存储过程。 执行后,它将在记录集中返回一些记录。 您应该将命令编写为

<pcommand>reptq1</pcommand>

或者,如果存储过程 reptq1 有两个参数 ab,您可以将 XML 中的命令字符串编写为

<pcommand>reptq1<a>valuea</a><b>valueb</b></pcommand>

解释器程序将自动创建 ADO 的 command 对象。

以下代码是调用 COM 对象的一个示例。

//Make the command 
reason_str ="<pcommand>reptq1</pcommand>";
// Ask the data and return XML to be processsed
xmlstr =xmlise.GetData (reason_str);

接口的属性和方法

COM 接口是用 ATL 编写的。 它具有以下方法

//List all columns in a specified table in a database.

HRESULT GetColumns(/*[in]*/BSTR tname,/*[out,retval]*/BSTR *out_xml);
  • tname: 指定的表名,用于查询列
  • out_xml: 表中的所有列信息,按列信息顺序排列。
//List all tables in specified database

HRESULT GetTables(/*[out,retval]*/ BSTR *out_xml);
  • out_xml: 包含数据库中所有表名的 XML 字符串
//List all stored procedure in specified database

HRESULT GetProcedures(/*[out,retval]*/ BSTR *out_xml);
  • out_xml: 包含数据库中所有存储过程名称的 XML 字符串
// List all catalogs in the database

HRESULT GetCatalogs(/*[out,retval]*/ BSTR *out_xml);
// Execute the command write in XML and get the command execute results

HRESULT GetData(/*[int]*/ BSTR in_xml, /*[out,retval]*/ BSTR *out_xml);
  • in_xml: 可以转换为命令的 XML 字符串
  • out_xml: 指定命令的执行结果

以下是当前 COM 接口的属性

  • ConnectionString: 数据源的 ADO 连接字符串
  • Password: 当前连接的数据源的密码
  • User: 具有指定密码以登录到数据库的用户

如何使用它?

以下是如何使用此 COM 接口的用法示例。

// Create a object to using COM object.
xmlise = Server.CreateObject ("DataEngine.DEng");
// Connection to old good database of SQL Server
xmlise.ConnectionString = _ 
  "PROVIDER=SQLOLEDB;DataSource=XMZY;Initial Catalog=pubs";
// Log in using  username  “SA” 
    xmlise.User  ="SA";
// the password of username is “”
    xmlise.Password ="";

// prepare the command to be executed.
    reason_str ="<pcommand>reptq1</pcommand>";

// Execute the command and get its result.
    xmlstr =xmlise.GetData (reason_str);

结论

XML 是一种适用于各种应用程序的通用技术。 制作轻便易用的 XML 处理工具非常重要。 这是值得的!

© . All rights reserved.