Mysql事务代码

        /// <summary>
        /// 删除相册
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool DeleAblumsById(long id)
        {
            int photo_Result = 0, ablums_Result = 0;
            string strSql_Photo = "delete from tb_photo where albumsId=" + id;
            string strSql_Ablums = "delete from tb_albums where id=" + id;
            MySqlTransaction tran = null;
            MySqlCommand com = null;
            MySqlConnection conn = null;
            try
            {
                conn = new MySqlConnection(_ConnectionString);
                conn.Open();
                tran = conn.BeginTransaction();
                com = new MySqlCommand(strSql_Photo, conn, tran);
                photo_Result = com.ExecuteNonQuery();

                com = new MySqlCommand(strSql_Ablums, conn, tran);
                ablums_Result = com.ExecuteNonQuery();
                if (photo_Result >= 0 && ablums_Result > 0)
                    tran.Commit();
            }
            catch (Exception)
            {
                tran.Rollback();
            }
            finally
            {
                tran.Dispose();
                conn.Close();
            }
            return photo_Result >= 0 && ablums_Result > 0;
        }

 

public static int ExecuteNonQuery(List<KeyValuePair<String, IEnumerable<MySqlParameter>>> strList, string connectionString)
        {
            int count = 0;
            using (MySqlConnection con = new MySqlConnection(connectionString))
            {
                con.Open();
                MySqlTransaction tran = con.BeginTransaction();
                MySqlCommand comm = new MySqlCommand();
                comm.Connection = con;
                comm.Transaction = tran;
                try
                {
                    strList.ForEach(o =>
                    {
                        comm.CommandText = o.Key;
                        IEnumerable<MySqlParameter> para = o.Value;
                        if (para != null)
                        {
                            foreach (var pa in para)
                                comm.Parameters.Add(pa);
                        }
                        count += comm.ExecuteNonQuery();
                        comm.Parameters.Clear();
                    });
                    tran.Commit();
                    return count;
                }
                catch (Exception)
                {
                    tran.Rollback();
                    return count;
                }
            }
        }

 

posted on 2014-02-10 14:52  朝着  阅读(473)  评论(0编辑  收藏  举报