SqlConnection conn = new SqlConnection("Data Source=****;Initial Catalog=****;User ID=***;Password=****"); conn.Open(); SqlCommand cmd = conn.CreateCommand(); SqlTransaction transaction = conn.BeginTransaction(); //开始事务 try { cmd.Connection = conn; cmd.Transaction = transaction; cmd.CommandType = CommandType.Text; cmd.CommandText = " select * from prediction_group (xlock) where prediction_date_ID=@prediction_date_ID"; cmd.Parameters.AddWithValue("@prediction_date_ID", 4); SqlDataReader reader2 = cmd.ExecuteReader(); reader2.Read(); string sample2 = reader2["sample2"].ToString(); reader2.Close(); cmd.CommandText = "update prediction_group set sample2 = '" + sample2 + "' WHERE ID =@ID"; cmd.Parameters.AddWithValue("@ID", 4); cmd.Parameters.AddWithValue("@sample2", 4); cmd.ExecuteNonQuery(); transaction.Commit(); //事务完成之后提交事务 } catch (Exception ex) { transaction.Rollback(); //如果事务没有完成,就回滚事务 throw; } finally { conn.Close(); }