【发布时间】:2009-09-18 08:02:20
【问题描述】:
我正在编写一个自定义 SSIS 任务,作为它的功能之一,它应该在数据库连接上执行一个存储过程。我似乎无法找到有关如何完成此操作的任何信息。
我正在使用 ADO.NET 连接管理器连接到数据库,我希望用 C# 编写我的任务。
在自定义 SSIS 任务中执行 SQL 的首选方式是什么?
【问题讨论】:
标签: sql sql-server sql-server-2008 ssis
我正在编写一个自定义 SSIS 任务,作为它的功能之一,它应该在数据库连接上执行一个存储过程。我似乎无法找到有关如何完成此操作的任何信息。
我正在使用 ADO.NET 连接管理器连接到数据库,我希望用 C# 编写我的任务。
在自定义 SSIS 任务中执行 SQL 的首选方式是什么?
【问题讨论】:
标签: sql sql-server sql-server-2008 ssis
这个问题的答案在某种程度上取决于您用于连接数据库的连接管理器,但一般方法是相同的:
Package 对象的Connections 属性在您的自定义任务中获取相关的连接管理器。 AcquireConnection 方法以获取到您的数据库的连接。此方法允许您利用 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;
}
}
您将需要更好的错误处理,但我不确定如何处理连接的生命周期,是应该手动打开它还是在使用后丢弃。
祝你好运!
【讨论】: