【问题标题】:What is the preferred way of executing SQL in a Custom SSIS task?在自定义 SSIS 任务中执行 SQL 的首选方式是什么?
【发布时间】:2009-09-18 08:02:20
【问题描述】:

我正在编写一个自定义 SSIS 任务,作为它的功能之一,它应该在数据库连接上执行一个存储过程。我似乎无法找到有关如何完成此操作的任何信息。

我正在使用 ADO.NET 连接管理器连接到数据库,我希望用 C# 编写我的任务。

在自定义 SSIS 任务中执行 SQL 的首选方式是什么?

【问题讨论】:

    标签: sql sql-server sql-server-2008 ssis


    【解决方案1】:

    这个问题的答案在某种程度上取决于您用于连接数据库的连接管理器,但一般方法是相同的:

    1. 使用Package 对象的Connections 属性在您的自定义任务中获取相关的连接管理器。
    2. 在连接管理器上调用AcquireConnection 方法以获取到您的数据库的连接。
    3. 使用提供的连接执行 SQL 语句。

    此方法允许您利用 SSIS 提供的连接配置和管理。

    对于 ADO.NET 连接管理器,可以使用以下代码:

    public override DTSExecResult Validate(
      Connections connections, VariableDispenser variableDispenser,
      IDTSComponentEvents componentEvents, IDTSLogging log)
    {
        // Validate connection exists.
        if(!connections.Contains("YourConnection"))
        {
            componentEvents.FireError(0, "CustomTask", 
                "Invalid connection manager.", "", 0);
            return DTSExecResult.Failure;
        }
    
        return DTSExecResult.Success;
    }
    
    public override DTSExecResult Execute(Connections connections, 
      VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, 
      IDTSLogging log, object transaction)
    {
        ConnectionManager cm = connections["YourConnection"];
    
        try
        {
            SqlConnection connection 
                = cm.AcqureConnection(transaction) as SqlConnection;
    
            if(connection == null)
            {
                componentEvents.FireError(0, "CustomTask", 
                    "Failed to acquire ADO.NET connection.", "", 0);
                Return DTSExecResult.Failure;
            }
    
            // TODO: Use connection to execute SQL.
        }
        catch(Exception ex)
        {
            componentEvents.FireError(0, "CustomTask", 
                ex.Message, "", 0);
    
            Return DTSExecResult.Failure;
        }
    }
    

    您将需要更好的错误处理,但我不确定如何处理连接的生命周期,是应该手动打开它还是在使用后丢弃。

    祝你好运!

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-30
      • 1970-01-01
      • 2017-01-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多