1. 程式人生 > >SQL Server事務操作(C#)

SQL Server事務操作(C#)

        事務是指使用者定義的一個數據庫操作序列,這些操作要麼全做要麼全不做,它是一個不可分割的工作單位。一個事務可以是一條SQL語句,一組SQL語句,或整個程式。

例子程式:

public bool transactionOp()
{
    // 事務成功返回true,事務失敗返回false
    bool result = false;
    string SqlConnectionString = "Data Source=.;Initial Catalog=DataBaseName;User ID=sa;pwd=123456;Connection Lifetime=0;max pool size=200";
    SqlConnection cn = new SqlConnection(SqlConnectionString);
    SqlCommand cmd = new SqlCommand();
    SqlTransaction transaction = null;

    try
    {
        // 開啟資料庫
        if (cn.State == ConnectionState.Closed)
        {
            cn.Open();
        }

        // 開始事務
        transaction = cn.BeginTransaction();
        cmd.Transaction = transaction;
        cmd.Connection = cn;

        // 執行第一條SQL語句
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "insert into Users values('admin', 'admin')";
        if (cmd.ExecuteNonQuery() < 0)
            throw new Exception();

        // 執行第二條SQL語句
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "update Users set pwd = '123456' where name = '小明'";
        if (cmd.ExecuteNonQuery() < 0)
            throw new Exception();

        // 提交事務
        transaction.Commit();
        result = true;
    }
    catch
    {
        result = false;
        // 回滾事務
        transaction.Rollback();
    }
    finally
    {
        // 關閉資料庫
        if (cn.State == ConnectionState.Open)
        {
            cn.Close();
        }
        cn.Dispose();
        cmd.Dispose();
        transaction.Dispose();
    }
    return result;
}