但是其并不是连接对象,不能直接作用于命令对象中,故需要强制转换为连接对象,如下代码: 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.
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