文章目录
- 第十二章 以编程方式使用 SQL 网关 - 直接调用 ODBC 函数
- 直接调用 ODBC 函数
- 使用 `%SQLGatewayConnection`方法中执行查询
第十二章 以编程方式使用 SQL 网关 - 直接调用 ODBC 函数
直接调用 ODBC 函数
如果%SQL.Statement 不能提供足够的控制,可以使用 %SQLGatewayConnection直接访问 ODBC。它提供了一组与 ODBC 函数相对应的方法以及其他实用程序函数。可以连接并使用兼容ODBC 的数据库,然后执行低级 ODBC 编程。整体流程如下:
- 通过
%New()方法创建%SQLGatewayConnection的实例。 - 调用该实例的
Connect()方法,传递指定ODBC数据源名称的参数,以及登录该源所需的用户名和密码(如有必要)。 - 调用
AllocateStatement()方法并接收(通过引用)语句句柄。 - 使用该语句句柄作为参数调用
SQL Gateway实例的其他方法。大多数这些方法调用ODBC函数。
以下简单示例演示了此过程。它与上一节中的示例类似,但它在版本的Prepare()和Execute()中使用%SQLGatewayConnection直接调用ODBC查询函数SQLPrepare()和SQLExecute(),而不是使用%SQL .Statement方法:
使用 %SQLGatewayConnection方法中执行查询
ClassMethod ExecuteQuery(mTable As %String)
{set mDSN="DSNtest"set mUsrName="SYSDBA"set mUsrPwd="masterkey"// Create an instance and connectset gateway=##class(%SQLGatewayConnection).%New()set status=gateway.Connect(mDSN,mUsrName,mUsrPwd)if $$$ISERR(status) do $System.Status.DisplayError(status) quit $$$ERROR()set hstmt=""// Allocate a statementset status=gateway.AllocateStatement(.hstmt)if $$$ISERR(status) do $System.Status.DisplayError(status) quit $$$ERROR()// Use %SQLGatewayConnection to call ODBC query functions directlyset status=gateway.Prepare(hstmt,"SELECT * FROM "_mTable)if $$$ISERR(status) do $System.Status.DisplayError(status) quit $$$ERROR()set status=gateway.Execute(hstmt)if $$$ISERR(status) do $System.Status.DisplayError(status) quit $$$ERROR()quit gateway.Disconnect()
}
注意:空值和空字符串
当使用本章中描述的方法时,请记住 IRIS 和 SQL 具有以下重要区别:
- 在
SQL中,""代表空字符串。 - 在
IRIS中,""等于null。 - 在
IRIS中,$char(0)等于空字符串。