用ADO.NET来使用事务

先把代码段记下来,省得到时候要用的时候再去翻硬盘中的源文件

string connString = WebConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
		SqlConnection conn = new SqlConnection(connString);
		conn.Open();
		SqlTransaction tran = conn.BeginTransaction();	//创建事务Transaction

		string strSQL = "INSERT INTO Employees(FirstName, LastName, City, Address) values (@paramFirstName,@paramLastName,@paramCity,@paramAddress)";
		SqlCommand cmd = new SqlCommand(strSQL, conn,tran);		//创建SqlCommand

		try
		{
			cmd.Parameters.Add("@paramFirstName", SqlDbType.NVarChar, 20).Value = txtFirstName.Text;
			cmd.Parameters.Add("@paramLastName", SqlDbType.NVarChar, 10).Value = txtLastName.Text;
			cmd.Parameters.Add("@paramCity", SqlDbType.NVarChar, 15).Value = txtCity.Text;
			cmd.Parameters.Add("@paramAddress", SqlDbType.NVarChar, 60).Value = txtAddress.Text;
			cmd.ExecuteNonQuery();
			tran.Commit();		//确认事务
            txtMsg.Text = "新增数据成功,事务确认!";
		}
		catch
		{
			tran.Rollback();   //事务回滚
            txtMsg.Text = "新增数据失败,事务Rollback!";
		}

		finally
		{
			conn.Close();
			conn.Dispose();
			tran.Dispose();
			cmd.Dispose();
		}
 

你可能感兴趣的:(.net)