几个常用得事务处理方法

 


    
/// <summary>
    
/// 启动事务
    
/// </summary>
    
/// <param name="cn">数据库连接</param>
    
/// <param name="cmd">命令对象</param>
    
/// <param name="transaction">事务</param>
    
/// <param name="executeString">Sql语句</param>
    
/// <returns></returns>

    public static int ExecuteNonQuery(DbConnection cn,DbCommand cmd,DbTransaction transaction,string executeString)
    
{
        
if (cn.State == ConnectionState.Closed)
        
{
            cn.Open();
        }

        cmd.Connection 
= cn;
        
if (transaction != null)
        
{
            cmd.Transaction 
= transaction;
        }

        cmd.CommandText 
= executeString;
        cmd.CommandType 
= CommandType.Text;
        
int i = cmd.ExecuteNonQuery();
        
return i;
    }

    
/// <summary>
    
/// 返回首行首列得值
    
/// </summary>
    
/// <param name="cn">数据库连接</param>
    
/// <param name="cmd">命令对象</param>
    
/// <param name="transaction">事务</param>
    
/// <param name="executeString">Sql语句</param>
    
/// <returns></returns>

    public static object ExecuteScalar(DbConnection cn, DbCommand cmd, DbTransaction transaction, string executeString)
    
{
        
if (cn.State == ConnectionState.Closed)
        
{
            cn.Open();
        }

        cmd.Connection 
= cn;
        
if (transaction != null)
        
{
            cmd.Transaction 
= transaction;
        }

        cmd.CommandText 
= executeString;
        cmd.CommandType 
= CommandType.Text;
        
object i = cmd.ExecuteScalar();
        
return i;
    }


    
/// <summary>
    
/// 返回一个DataReader
    
/// </summary>
    
/// <param name="cn">数据库连接</param>
    
/// <param name="cmd">命令对象</param>
    
/// <param name="transaction">事务</param>
    
/// <param name="executeString">Sql语句</param>
    
/// <returns></returns>

    public static DbDataReader ExecuteReader(DbConnection cn, DbCommand cmd, DbTransaction transaction, string executeString)
    
{
        
if (cn.State == ConnectionState.Closed)
        
{
            cn.Open();
        }

        cmd.Connection 
= cn;
        
if (transaction != null)
        
{
            cmd.Transaction 
= transaction;
        }

        cmd.CommandText 
= executeString;
        cmd.CommandType 
= CommandType.Text;
        DbDataReader reader 
= cmd.ExecuteReader();
        
return reader;
    }

如果要用到上面这此只是给它几个参数就行了,成功就Commit一下,不成功就Rollback一下.

如:

        DbConnection cn = GetConnection();
        if (cn.State == ConnectionState.Closed)
        {
            cn.Open();
        }
        DbTransaction transaction = cn.BeginTransaction(IsolationLevel.ReadCommitted);
        DbCommand cmd = GetCommand();

      XXX.ExecuteNonQuery(cn, cmd, transaction, executeString) 判断这个就可以了.

posted on 2007-03-18 00:43  小土泥  阅读(216)  评论(0编辑  收藏  举报

导航