5

几天来我一直在寻找解决方案,但似乎仍然找不到。我在脚本组件中获取连接时遇到问题。我需要查询我的数据库以检索要使用的 Id,然后再将其插入

public override void AcquireConnections(object Transaction)
{
    connMgr = base.Connections.Connection;
    conn =  (SqlConnection)connMgr.AcquireConnection(null);
}

我在这里得到一个例外。

System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to class type 'System.Data.SqlClient.SqlConnection'. 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.

有什么解决办法吗?

4

2 回答 2

7

对于那些希望能够在脚本组件中执行此操作的人:

  1. 双击脚本组件打开“脚本转换编辑器”
  2. 单击“连接管理器”列表项。
  3. 添加新的连接管理器。选择现有的 ADO.NET 连接管理器。
  4. 单击“脚本”列表项,然后单击“编辑脚本...”按钮。

您可以在脚本中执行以下操作:

using (SqlConnection connection = this.Connections.Connection.AcquireConnection(null) as SqlConnection)
{
    using (SqlCommand command = connection.CreateCommand())
    {
        command.CommandText = "SELECT [Value] FROM dbo.MyTable";
        command.CommandType = CommandType.Text;

        using (SqlDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                ProfanityWords.Add(reader.GetValue(0).ToString());
            }
        }
    }

    this.Connections.Connection.ReleaseConnection(connection);
}

在此处输入图像描述

于 2014-10-27T05:25:02.037 回答
2

应创建 ADO.NET 连接管理器并参考代码以将类型转换为SqlConnection. 如果您的 SSIS 包中没有 ADO.NET 连接,您将收到 TypeCast 异常。如果要使用 SqlConnection,应使用以下步骤。

  1. 创建 ADO.NET 连接。
  2. 在您的代码中使用以下行。

    var connObj = Dts.Connections["ADO.NETConnectionName"].AcquireConnection(null);
    
    var sqlConn = (SqlConnection)connObj;
    
  3. 完成 SQL 连接后。使用以下代码关闭/释放您的连接。

    Dts.Connections["ADO.NETConnectionName"].ReleaseConnection(connObj);
    

希望这可以帮助。

于 2012-11-27T08:51:05.790 回答