2012-11-27 128 views
5

我一直在尋找解決方案,現在我仍然無法找到一個。我的腳本組件中有一個連接問題。我需要查詢我的數據庫以檢索要使用的Id,然後將其插入到SSIS腳本組件連接

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. 

任何解決方案?

回答

4

對於那些希望能夠做到這一點的腳本組件:

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

enter image description here

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

希望這有助於。

+0

感謝您的答覆,但我的主要問題是,我沒有看到班裏的「DTS」對象。即使我將.dts包含在參考文獻中。 –

+0

答案與腳本組件無關,對此問題提出了問題。而是關於一個略有不同的腳本任務。 –

+0

詳細論述@ MaximV.Pavlov的評論 - 與腳本_component_(存在於Dataflow任務中)有關的問題,而這個答案與腳本_task_(存在於控制流中)有關。 – Sepster