在C#中使用动态拼接sql-IN语句
好好生活 工作开心就好~
事务方法:
/// <summary> /// 事务2 - 声明参数 ///demo: ///dic.Add("Insert into Users values (@UserName, @Email, @Address)", /// new { UserName = "张三", Email = "888888888@qq.com", Address = "北京" }); /// </summary> /// <param name="Key">多条SQL</param> /// <param name="Value">param</param> /// <returns></returns> public static int ExecuteTransaction(Dictionary<string, object> dic) { using (IDbConnection con = new MySqlConnection(MySqlConnStr)) { if (con.State != ConnectionState.Open) { con.Open(); } using (var transaction = con.BeginTransaction()) { try { int result = 0; foreach (var sql in dic) { result += con.Execute(sql.Key, sql.Value, transaction); } transaction.Commit(); return result; } catch (Exception ex) { //MyLog.Logger_Error(ex); transaction.Rollback(); return 0; } } } }
使用事务拼接in语句:
public static bool QtupdateShowState(int userId, List<int> devices) { Dictionary<string, object> dic = new Dictionary<string, object>(); string updateShowsqlstr = $"update user_device_mapping set Is_Show=1 where user_Id=@userId and dev_id in({String.Join(",",devices)}) and Is_del=0"; string UnupdateShowsqlstr = $"update user_device_mapping set Is_Show=0 where user_Id=@userId and dev_id not in({String.Join(",",devices)}) and Is_del=0"; var data = new { userId = userId, devices = String.Join(",", devices) }; dic.Add(updateShowsqlstr, data); dic.Add(UnupdateShowsqlstr, data); int Is_true = MySqlDBHelper<user_device_mapping>.ExecuteTransaction(dic); if (Is_true>0) { return true; } return false; }
调用方法:
static void Main(string[] args) { List<int> devicelist = new List<int>() { 12,7,5,13 }; QtupdateShowState(2, devicelist); Console.WriteLine("执行完成~"); Console.ReadLine(); }