string connString = WebConfigurationManager.ConnectionStrings"ConnectionString".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(); }