我应该如何在 SSIS 数据流任务的“脚本组件”中使用连接管理器。我尝试使用带有 OLEDB 提供程序和 SQL 的连接管理器,但失败了。正确的使用方法是什么,或者应该如何做?
脚本任务和脚本组件之间的语法不同。查看这篇文章,了解更多并排比较:
MSDN 上对此有详细记录,涵盖 VB 和 C# 类型的脚本:http://msdn.microsoft.com/en-us/library/ms136018.aspx
IDTSConnectionManager100 connMgr = this.Connections.ADONetAppStaging ; //this we need to give name in connection manager in script component
SqlConnection myADONETConnection = new SqlConnection();
myADONETConnection = (SqlConnection)(connMgr.AcquireConnection(null));
//Read data from table or view to data table
string query = "Select top 10 * From ##AP_Stagging_Temp_ExportWODuplicates Order by 1,2,3 asc ";
// string query = "Select * From ##AP_Stagging_Temp_For_JLL_ExportWODuplicates order by 1,2,3 asc ";
SqlDataAdapter adapter = new SqlDataAdapter(query, myADONETConnection);
DataTable dtExcelData = new DataTable();
adapter.Fill(dtExcelData);
myADONETConnection.Close();
在此处的 Q/A 和 It's possible to use OleDbConnections with the Script Component?.
的帮助下,我让它开始工作了?这里是占用脚本组件的连接管理器的代码,这样你就不需要再写连接字符串了:
using System;
using System.Data;
using System.Data.OleDb;
using Microsoft.SqlServer.Dts.Pipeline.Wrapper;
using Microsoft.SqlServer.Dts.Runtime.Wrapper;
using Microsoft.SqlServer;
using Microsoft.SqlServer.Dts;
using System.Data.SqlClient;
[Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute]
public class ScriptMain : UserComponent
{
//private OleDbConnection conn;
//private OleDbDataAdapter adapter;
//private DataTable tempTable;
private IDbConnection conn;
private string connectionString;
public override void AcquireConnections(object Transaction)
{
base.AcquireConnections(Transaction);
// Access the connection manager by name
IDTSRuntimeConnectionCollection100 runtimeConnectionCollection = ComponentMetaData.RuntimeConnectionCollection;
IDTSRuntimeConnection100 tempDbRuntimeConnection = runtimeConnectionCollection["tempdb"];
// Acquire the connection
if (tempDbRuntimeConnection.ConnectionManager != null)
{
conn = tempDbRuntimeConnection.ConnectionManager.AcquireConnection(null) as IDbConnection;
connectionString = conn.ConnectionString;
}
else
{
throw new Exception("Failed to acquire connection");
}
}
... more code ...
其他答案已经展示的一个技巧是建立 ADO.NET 连接而不是 OLE DB 连接。
另一个技巧是避免 智能感知在
IDTSConnectionManager100 tempDbConnectionManager = this.ComponentMetaData.RuntimeConnectionCollection["tempdb"];
处显示红色下划线。 Intellisense 表示它无法隐式键入 ... PipelineConnectionCollection ...
来键入 ... RuntimeConnectionCollection ...
。
这可以通过更改代码来解决:
IDTSConnectionManager100 tempDbConnectionManager = this.ComponentMetaData.RuntimeConnectionCollection["tempdb"];
至:
IDTSRuntimeConnectionCollection100 runtimeConnectionCollection = ComponentMetaData.RuntimeConnectionCollection;
IDTSRuntimeConnection100 tempDbRuntimeConnection = runtimeConnectionCollection["tempdb"];