用于CRUD操作和事务的简单SQL连接类

时间:2013-07-04 08:48:53

标签: c# sql-server

我一直在尝试为一个小项目编写一个sql连接类,它将使用简单的sql命令进行插入/更新/选择/删除操作,有时使用事务,是否有任何指导我可以使用?可以在有或没有事务的任何时候实例化该类......

尝试:

public class DbConnection

{
    public static string srConnectionString = "blablab";

public DbConnection()
{

}

public static DataSet db_Select_Query(string strQuery)
{
    DataSet dataSet = new DataSet();

    try
    {
        using (SqlConnection connection = new SqlConnection(srConnectionString))
        {
            connection.Open();
            SqlDataAdapter _SqlDataAdapter = new SqlDataAdapter(strQuery, connection);
            DA.Fill(dataSet);
        }
        return dataSet;
    }

    catch (Exception)
    {
         //some error handling.
    }
}

public static void db_Update_Delete_Query(string strQuery)
{
    try
    {
        using (SqlConnection connection = new SqlConnection(srConnectionString))
        {
            connection.Open();
            SqlCommand command = new SqlCommand(strQuery, connection);
            command.ExecuteNonQuery();
        }
    }
    catch (Exception)
    {
         //some error handling.
    }
}

例如,如果使用此类,我如何添加打开或关闭事务的参数?例如,我可以从类外部调用db.commit或db.rollback。

PS:试过一些微观问题(例如petapoco),有没有办法用纯sql运行它们并获得返回类型只作为数据集或数据表?

问候。

编辑:

  public class dbconnection : IDisposable
{
    public static string strConnectionString = @"Data Source=PC137\PC137_SQL2008;Initial Catalog=BARZO;Integrated Security=True";

    #region IDisposable Members

    public void Dispose()
    {
        GC.SuppressFinalize(this);
    }

    #endregion

    private SqlTransaction transaction;
    private SqlConnection connection;
    private SqlCommand command = new SqlCommand();


    public void db_OpenConnection(bool WithTransaction)
    {
        connection = new SqlConnection(strConnectionString);
        connection.Open();

        if (WithTransaction)
        {
            transaction = connection.BeginTransaction();
        }
    }


    public void db_CloseConnection()
    {
        connection.Close();
        connection.Dispose();
        transaction.Dispose();
        command.Dispose();
    }


    public void db_Commit()
    {
        transaction.Commit();
    }


    public void db_RollBack()
    {
        transaction.Rollback();
    }


    public DataSet db_Select_Query(string strQuery)
    {
        var dataSet = new DataSet();

        try
        {
            SqlDataAdapter SqlDataAdapter = new SqlDataAdapter(strQuery, connection);
            SqlDataAdapter.Fill(dataSet);
            return dataSet;
        }

        catch (SqlException sqlError)
        {
            MessageBox.Show(sqlError,MessageBoxButtons.OK, MessageBoxIcon.Stop);
        }
    }

    public bool db_Update_Delete_Query(string strQuery)
    {
        try
        {
            command = new SqlCommand(strQuery, connection);
            command.Transaction = transaction;
            command.ExecuteNonQuery();
        }
        catch (SqlException sqlError)
        {
            MessageBox.Show(sqlError,MessageBoxButtons.OK, MessageBoxIcon.Stop);
            return false;
        }
        return true;
    }
}

1 个答案:

答案 0 :(得分:1)

我会使db_Update_Delete_Query()方法返回您自己的DbCommandToken,它包装SqlTransaction对象,并可用于取消事务或报告命令的完成。

这看起来像这样。

public class DbConnection
{
    public static DbCommandToken db_Update_Delete_Query(string strQuery)
    {
        try
        {
            using (SqlConnection connection = new SqlConnection(strConnectionString))
            {
                connection.Open();
                var transaction = connection.BeginTransaction();
                SqlCommand command = new SqlCommand(strQuery, connection);
                return new DbCommandToken(transaction, command);
            }
        }
        catch (Exception)
        {
            //some error handling.
        }
    }
}

请注意,您的DbCommandToken对象现在拥有您的命令和您的交易,该对象应该实现IDisposable

如果您的命令是一个长时间运行的命令,您可能希望异步运行,并且可能会在以后的请求中取消,则可以向DbCommandToken添加成功和失败回调:这些内容。< / p>

public class DbCommandToken : IDisposable
{
    private readonly SqlTransaction _transaction;
    private readonly SqlCommand _command;

    public DbCommandToken(SqlTransaction transaction, SqlCommand command)
    {
        _transaction = transaction;
        _command = command;
    }

    public Action Success { get; set; }

    public Action Failure { get; set; }

    public Task<int> Execute()
    {
        return Task.Factory.StartNew(() => _command.ExecuteNonQuery())
            .ContinueWith(t =>
                {
                    var rowsAffected = t.Result;
                    if (rowsAffected >= 0)
                    {
                        _transaction.Commit();
                        Success();
                    }

                    ...Handle other scenarios here...

                    return t.Result;
                });
    }

    public void Cancel()
    {
        _transaction.Rollback();
    }

    public void Dispose()
    {
        _command.Dispose();
        _transaction.Dispose();
    }
}