2009-09-18 61 views
3

我在写一个自定义SSIS任务,作为它的一个函数,它应该在数据库连接上执行一个存储过程。我似乎无法找到有关如何完成的任何信息。在自定义SSIS任务中执行SQL的首选方式是什么?

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

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

回答

5

这个问题的答案一定程度上取决于您使用连接到数据库中的哪些连接管理器,但一般的方法是一样的:

  1. 使用Connections属性获取有关连接管理器在您的自定义任务的Package对象。
  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; 
    } 
} 

你会想一些更好的错误处理,我不知道如何处理连接的使用寿命,无论是你应该手动打开它或在使用后丢弃。

祝你好运!

相关问题