Farseer

导航

在Axapta中使用Direct SQL

有时候需要操作Axapta数据库以外的数据库里的信息,这个时候无论用X++里的select还是Query都没办法做到,只能采用Direct SQL.Axapta提供了Connection,UserConnection和ODBCConnection三个对象用于执行Direct SQL.
下面是帮助文档中对这三个对象的描述:
1.Connection
A Connection represents the current session with the SQL database. Within the context of a Connection, SQL statements are executed and results are returned.
这个连接是Axapta与SQL数据库的当前会话.在这个连接的上下文,可以执行SQL语句并得到结果.
2.UserConnection
A UserConnection represents an auxiliary connection to the SQL database, based on the same login properties as the main connection. Within the context of a UserConnection, SQL statements are executed and results are returned.UserConnections can be used to obtain a separate transaction scope.
基于原主连接的属性创建的辅助连接,可以获得一个单独的事物范围.
3.ODBCConnection
An OdbcConnection establishes a database connection using ODBC (Open Database Connectivity). Within the context of an OdbcConnection, SQL statements are executed and results are returned. In order to work, the proper ODBC drivers must have been installed and configured in the ODBC Manager in the Control Panel.
通过ODBC创建链接.当然适当的ODCB驱动必须通过控制面板里的ODBC管理器安装和配置.
我在做的时候采用了Connection,使用原有的数据库连接会话.
当然有时候数据库服务器有可能跟Axapta数据库服务器不是一台,需要通过链接服务器把需要访问的数据库服务器链接到Axapta数据库服务器,在SQL语句中用serverName.databsaeName.dbo.TableName的方式访问.
以下是示例代码:
static server void DirectSQL()
{
     Connection Con;
     Statement Stmt;
     ResultSet R;
     str sqlString;
     ;
    sqlString 
='SELECT * FROM [dbServer].[axapta2].dbo.userInfo';

    Con  
= new Connection();
    Stmt 
= Con.createStatement();
    R 
= Stmt.executeQuery(sqlString);

    
while ( R.next() )
    
{
        print R.getString(
1);
    }

    pause;
}

上面的代码在Axapta3.0中可以顺利运行,不管上面的代码是运行在client还是server端.但在Axapta4.0中,Axapta不允许client直接访问数据库,并且Direct SQL被视为危险的API,所以必须用SqlStatementExecutePermission的asset()来限制SQL语句的执行,否则上述代码将不能执行,这点在Writing Secure X++ Code(一)中有介绍,Axapta4.0的代码如下:
static server void DirectSQL()
{
     Connection Con;
     Statement Stmt;
     ResultSet R;
     str sqlString;
     ;
    sqlString 
='SELECT * FROM [dbServer].[axapta2].dbo.userInfo';
    
    
new SqlStatementExecutePermission(sqlString).assert();
    Con  
= new Connection();

    Stmt 
= Con.createStatement();
    R 
= Stmt.executeQuery(sqlString);

    
while ( R.next() )
    
{
        print R.getString(
1);
    }

    pause;
}

posted on 2006-09-20 19:47  佛西亚  阅读(1228)  评论(10编辑  收藏  举报