0

我最初发布问题是为了检查是否存在 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();
    }
}

}

4

2 回答 2

1

由于connections[_connectionName].AcquireConnection(transaction);你的代码部分与 a 无关SqlConnection(你只是在SqlConnection之后转换),你应该能够声明connectionvar然后做任何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
}
于 2012-06-26T22:42:12.713 回答
1

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

如果你使用这些,即。DbConnection,无论您使用哪种具体实现,代码都是相同的。

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

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

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

您的其余代码也可以使用基本类型,所以DbTransactionDbDataAdapter等等DbDataReader

因为您的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-26T22:47:59.910 回答