【问题标题】:Check for either ADO.NET / OLEDB Connection presence and then insert to DB检查 ADO.NET / OLEDB 连接是否存在,然后插入 DB
【发布时间】:2012-06-28 07:50:48
【问题描述】:

我最初发布 question 是为了检查是否存在 ADO.NET/OLEDB 连接类型。我想知道,在插入数据库时​​如何更改代码。

例如,当连接类型为 ADO.NET 时,我们在连接类型中使用“Transaction”。

 SqlConnection connection = (SqlConnection)connections[_connectionName].AcquireConnection(transaction);

现在,如果我有 OLEDB 连接(而不是 ADO.NET),我想在这段代码中处理这种情况。我需要做什么。对不起,如果我听起来不够技术,但我不是 C# 人。再次感谢您的热心帮助。

编辑 我在这里粘贴整个代码,因为我似乎无法使用 OLEDB 类型的连接。我只能使用 ADO.NET...我知道它很简单,但我不知道它是什么。

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Dts.Runtime;
using System.Data.OleDb;
using System.Data.Common;

namespace AOC.SqlServer.Dts.Tasks

{

[DtsTask(
    DisplayName = "Custom Logging Task",
    Description = "Writes logging info into a table")]
public class CustomLoggingTask : Task
{

    private string _packageName;
    private string _taskName;
    private string _errorCode;
    private string _errorDescription;
    private string _machineName;
    private double _packageDuration;

    private string _connectionName;
    private string _eventType;
    private string _executionid;
    private DateTime _handlerdatetime;
    public string ConnectionName
    {
        set
        {
            _connectionName = value;
        }
        get
        {
            return _connectionName;
        }
    }


    public string Event
    {
        set
        {
            _eventType = value;
        }
        get
        {
            return _eventType;
        }
    }


    public override DTSExecResult Validate(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log)
    {
        const string METHOD_NAME = "CustomLoggingTask-Validate";

        try
        {

            if (string.IsNullOrEmpty(_eventType))
            {
                componentEvents.FireError(0, METHOD_NAME, "The event property must be specified", "", -1);
                return DTSExecResult.Failure;
            }


            if (string.IsNullOrEmpty(_connectionName))
            {
                componentEvents.FireError(0, METHOD_NAME, "No connection has been specified", "", -1);
                return DTSExecResult.Failure;
            }

            DbConnection connection = connections[_connectionName].AcquireConnection(null) as DbConnection;
            if (connection == null)
            {
                componentEvents.FireError(0, METHOD_NAME, "The connection is not a valid ADO.NET connection", "", -1);
                return DTSExecResult.Failure;
            }

            if (!variableDispenser.Contains("System::SourceID"))
            {
                componentEvents.FireError(0, METHOD_NAME, "No System::SourceID variable available. This task can only be used in an Event Handler", "", -1);
                return DTSExecResult.Failure;
            }

            return DTSExecResult.Success;
        }
        catch (Exception exc)
        {
            componentEvents.FireError(0, METHOD_NAME, "Validation Failed: " + exc.ToString(), "", -1);
            return DTSExecResult.Failure;
        }
    }


    public override DTSExecResult Execute(Connections connections, VariableDispenser variableDispenser, IDTSComponentEvents componentEvents, IDTSLogging log, object transaction)
    {
        try
        {
            string commandText =
@"INSERT INTO SSISLog (EventType, PackageName, TaskName, EventCode, EventDescription, PackageDuration, Host, ExecutionID, EventHandlerDateTime)
VALUES (@EventType, @PackageName, @TaskName, @EventCode, @EventDescription, @PackageDuration, @Host, @Executionid, @handlerdatetime)";

            ReadVariables(variableDispenser);
            DbConnection connection = connections[_connectionName].AcquireConnection(transaction) as DbConnection;
            //SqlConnection connection = (SqlConnection)connections[_connectionName].AcquireConnection(transaction);
            DbCommand command = null;
            //using (SqlCommand command = new SqlCommand())
            if (connection is SqlConnection)
                command = new SqlCommand();
            else if (connection is OleDbConnection)
                command = new OleDbCommand();

            {
                command.CommandText = commandText;
                command.CommandType = CommandType.Text;
                command.Connection = connection;

                command.Parameters.Add(new SqlParameter("@EventType", _eventType));
                command.Parameters.Add(new SqlParameter("@PackageName", _packageName));
                command.Parameters.Add(new SqlParameter("@TaskName", _taskName));
                command.Parameters.Add(new SqlParameter("@EventCode", _errorCode ?? string.Empty));
                command.Parameters.Add(new SqlParameter("@EventDescription", _errorDescription ?? string.Empty));
                command.Parameters.Add(new SqlParameter("@PackageDuration", _packageDuration));
                command.Parameters.Add(new SqlParameter("@Host", _machineName));
                command.Parameters.Add(new SqlParameter("@ExecutionID", _executionid));
                command.Parameters.Add(new SqlParameter("@handlerdatetime", _handlerdatetime));
                command.ExecuteNonQuery();
            }

            return DTSExecResult.Success;
        }
        catch (Exception exc)
        {
            componentEvents.FireError(0, "CustomLoggingTask-Execute", "Task Errored: " + exc.ToString(), "", -1);
            return DTSExecResult.Failure;
        }
    }


    private void ReadVariables(VariableDispenser variableDispenser)
    {
        variableDispenser.LockForRead("System::StartTime");
        variableDispenser.LockForRead("System::PackageName");
        variableDispenser.LockForRead("System::SourceName");
        variableDispenser.LockForRead("System::MachineName");
        variableDispenser.LockForRead("System::ExecutionInstanceGUID");
        variableDispenser.LockForRead("System::EventHandlerStartTime");
        bool includesError = variableDispenser.Contains("System::ErrorCode");
        if (includesError)
        {
            variableDispenser.LockForRead("System::ErrorCode");
            variableDispenser.LockForRead("System::ErrorDescription");
        }

        Variables vars = null;
        variableDispenser.GetVariables(ref vars);

        DateTime startTime = (DateTime)vars["System::StartTime"].Value;
        _packageDuration = DateTime.Now.Subtract(startTime).TotalSeconds;
        _packageName = vars["System::PackageName"].Value.ToString();
        _taskName = vars["System::SourceName"].Value.ToString();
        _machineName = vars["System::MachineName"].Value.ToString();
        _executionid = vars["System::ExecutionInstanceGUID"].Value.ToString();
        _handlerdatetime = (DateTime)vars["System::EventHandlerStartTime"].Value;
        if (includesError)
        {
            _errorCode = vars["System::ErrorCode"].Value.ToString();
            _errorDescription = vars["System::ErrorDescription"].Value.ToString();
        }

        // release the variable locks.
        vars.Unlock();

        // reset the dispenser
        variableDispenser.Reset();
    }
}

}

【问题讨论】:

    标签: c# ado.net ssis oledb custom-component


    【解决方案1】:

    由于您的代码中的connections[_connectionName].AcquireConnection(transaction); 部分与SqlConnection 无关(之后您只是转换为SqlConnection),您应该能够使用var 声明connection,然后执行connection 的任何内容都需要。

    var connection = connections[_connectionName].AcquireConnection(transaction);
    

    一旦您有了connection 对象,您就可以将其转换为您需要的任何连接类型,并执行与您已将connection 变量声明为该类型一样的操作。例如

    if(connection is DbConnection)
    {
        // ((DbConnection)connection).SomethingToDoWithDbConnection
    }
    
    if(connection is SqlConnection)
    {
        // ((SqlConnection)connection).SomethingToDoWithSqlConnection
    }
    
    if(connection is OleDbConnection)
    {
        // ((OleDbConnection)connection).SomethingToDoWithOleDbConnection
    }
    

    【讨论】:

      【解决方案2】:

      System.Data.Common 中,您将找到具体数据库类型(SqlConnection、OleDbConnection、SqlDataAdapter 等)都派生自的基类。

      如果你使用这些,即。 DbConnection,不管你使用的是哪个具体的实现,代码都是一样的。

      DbConnection connection = connections[_connectionName]
          .AcquireConnection(transaction) as DbConnection;
      

      然后,您可以调用DbConnection.BeginTransaction() 而不是SqlConnection.BeginTransaction(),连接是OleDbConnection 还是SqlConnection 都没有关系。

      只要您需要调用的所有方法都继承自 DbConnection,这将起作用。

      您的其余代码也可以使用基本类型,例如DbTransactionDbDataAdapterDbDataReader 等。

      因为您的 AquireConnection() 方法不返回具体的连接类型,您可以利用依赖注入并编写非特定于实现的代码。


      具体来说,对于插入,您将拥有如下内容:

      DbCommand command = null;
      if (connection is SqlConnection)
         command = new SqlCommand();
      else if (connection is OleDbConnection)
         command = new OleDbCommand();
      command.CommandText = "INSERT STATEMENT HERE";
      command.Connection = connection;
      command.ExecuteNonQuery();
      

      别忘了你会在某个地方需要connection.Close()。 (如果您使用的是 ConnectionManager,则为 ReleaseConnection)

      【讨论】:

        猜你喜欢
        • 2012-06-28
        • 2017-04-27
        • 1970-01-01
        • 1970-01-01
        • 2015-04-02
        • 1970-01-01
        • 2016-03-24
        • 1970-01-01
        • 2010-11-01
        相关资源
        最近更新 更多