◆在上文中我们知道了如何在脚本组件中访问包...... 在上文中我们知道了如何在脚本组件中访问包变量,但在其中访问数据连接应该怎么办呢? 通过查看DTS类的属性我们知道其有一个 Connections 属性,其对应的正是SSIS设计面板中连接管理器中连接的映射 比如我们在连接管理器中建立一个 ADO.NET 的连接,命名为 connect1 那么在组件代码中我们就可以通过下面2种方式访问这个连接,如下 Dts.Connections(0) 或者 Dts.Connections("connect1") 但是其并不是连接对象,不能直接作用于命令对象中,故需要强制转换为连接对象,如下代码: Dim sqlConn As SqlConnection sqlConn = CType(Dts.Connections(0).AcquireConnection(Nothing), SqlConnection) 需要注意,不能直接CType(Dts.Connections(0), SqlConnection),需要用该对象的AcquireConnection方法获得一个连接,再强制转换 好了,现在已经转换为连接对象,你可以使用如下代码再该连接中执行命令 Dim command As New SqlClient.SqlCommand command.Connection = sqlConn command.CommandType = CommandType.Text command.CommandText = "你的命令" command.ExecuteNonQuery() command = Nothing 本来到此就应该结束此文了,但是可惜的是还要继续下去 上面提到的是在连接管理器中建立一个ADO.NET的连接,如果你建立一个OLE.DB的连接,在运行上面代码,你会得到下面错误: Unable to cast COM object of type 'System.Data.OleDb.OleDbConnection' to class type ''. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface. 上面的大概意思就是说,不能进行强制类型转换,当前对象没有提供这样的接口 明白了把,就是说不行,也就是说你建立的是OLE.DB连接,那么 AcquireConnection 方法返回的也是一个 OLE.DB的连接对象,你不能用SqlConnection去替代它 怎么办呢,解决方法有二 一是把OLE.DB连接对象的类型找出来,并引用上它,然后再用它强制转换,但是可惜的是我不知道怎么样才能。。。。; 二就是建立一个ADO.NET的连接好了,可是我又怕它是不是会比OLE.DB的连接处理速度要慢,所以之后通融一下了,代码如下 Public Class ScriptMain Public Sub Main() Dim command As New SqlClient.SqlCommand Dim cn As New SqlClient.SqlConnection MsgBox(Dts.Connections(0).ConnectionString) cn.ConnectionString = "" + Dts.Connections(0).ConnectionString cn.Open() MsgBox(Err.Description) command.Connection = cn command.CommandType = CommandType.Text command.CommandText = "insert into pay_dur(code) values('1')" command.ExecuteNonQuery() command = Nothing cn.Close() End Sub 好了,到此结束了,如果你知道第一种解决方法或者还有其他解决方法,还请指点,非常感谢 |
|小黑屋|最新主题|手机版|微赢网络技术论坛 ( 苏ICP备08020429号 )
GMT+8, 2024-9-29 19:17 , Processed in 0.250055 second(s), 12 queries , Gzip On, MemCache On.
Powered by Discuz! X3.5
© 2001-2023 Discuz! Team.