C#使用事務批量操作例項
阿新 • • 發佈:2019-02-13
C#基礎語法系列- C#事務
業務描述: 寫一個 批量插入方法,InsertList, 事務中執行insert方法(單個插入)。
/// <summary>
/// 批量插入操作
/// </summary>
/// <param name="userList">列表</param>
/// <returns></returns>
public bool Insert(List<User> userList)
{
bool isSuccess = true;
using (SqlConnection conn = new SqlConnection(Config.DBConn))
{
conn.Open();
SqlTransaction tran = conn.BeginTransaction();
try
{
foreach (var item in userList)
{
//*執行單個插入方法
int result = Insert(item, tran);
}
tran.Commit();
}
catch (Exception ex)
{
//rollback
tran.Rollback();
isSuccess = false;
}
}
return isSuccess;
}
/// <summary>
/// 單行插入
/// </summary>
/// <param name="user">單行</param>
/// <returns></returns>
public bool Insert(User user, SqlTransaction transaction)
{
string sql = @"insert into Table(Attribute)values(@Attribute)";
List<SqlParameter> param = new List<SqlParameter>();
param.Add(new SqlParameter() { ParameterName = "@Attribute", DbType = DbType.String, SqlValue = value });
formalSql = string.Format(sql, valueStr, paramStr);
/*此處執行插入方法*/
int result = DBOptExtend.ExecuteNonQuery(formalSql, transaction, param.ToArray());
return result > 0;
}
/// <summary>
/// 資料庫操作方法擴充套件
/// </summary>
public class DBOptExtend
{
/// <summary>
///執行查詢
/// </summary>
/// <param name="sentence">sql語句</param>
/// <param name="transaction">事務</param>
/// <param name="parameters">引數</param>
/// <returns></returns>
public static int ExecuteNonQuery(string sentence, SqlTransaction transaction, DbParameter[] parameters = null)
{
using (SqlCommand cmd = new SqlCommand(sentence))//modify by wsy
{
cmd.Transaction = transaction;
cmd.Connection = transaction.Connection;
if (parameters != null)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
int result = Convert.ToInt32(cmd.ExecuteNonQuery());
return result;
}
}
}