【问题标题】:SSIS Script Component connectionSSIS 脚本组件连接
【发布时间】:2012-11-27 06:07:39
【问题描述】:

我这几天一直在寻找解决方案,但似乎仍然找不到。我在脚本组件中获取连接时遇到问题。我需要先查询我的数据库以检索要使用的 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.

有什么解决办法吗?

【问题讨论】:

    标签: ssis database-connection script-component


    【解决方案1】:

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

    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);
    }
    

    【讨论】:

      【解决方案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);
        

      希望这会有所帮助。

      【讨论】:

      • 感谢您的回复,但我的主要问题是我在课堂上看不到“Dts”对象。即使我在引用中包含 .dts。
      • Answer 与询问问题的脚本组件无关。相反,它是关于一个稍微不同的脚本任务。
      • 详细说明@MaximV.Pavlov 的评论 - 与脚本 component (存在于 Dataflow 任务中)相关的问题,而此答案与脚本有关 task(存在于控制流中)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-20
      • 2020-11-06
      • 1970-01-01
      • 1970-01-01
      • 2022-10-12
      • 1970-01-01
      相关资源
      最近更新 更多