C# mysql 事务处理

 try
            {
                using (MySqlConnection conn = new MySqlConnection("Database=Database;Data Source=127.0.0.1;User Id=root;Password=123456;pooling=false;CharSet=utf8"))
                {
                    conn.Open();
                    MySqlTransaction transaction = conn.BeginTransaction();


                    MySqlCommand cmd = conn.CreateCommand();
                    cmd.Transaction = transaction;

                    try
                    {
                        cmd.CommandText = "INSERT INTO people(name,age,sex) VALUES('张三','18','2')";
                        int x = cmd.ExecuteNonQuery();
                        cmd.CommandText = "INSERT INTO address(address) VALUES('ddddddd')";
                        int y = cmd.ExecuteNonQuery();
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        try
                        {
                            transaction.Rollback();
                        }
                        catch (Exception en)
                        {

                            throw;
                        }

                    }

                }
            }
            catch (Exception)
            {

                throw;
            }

 

posted @ 2018-12-24 11:54  sanpi1992  阅读(4078)  评论(0编辑  收藏  举报