美文网首页
C#代码实现MySQL事务例子

C#代码实现MySQL事务例子

作者: norman1981 | 来源:发表于2017-09-20 13:54 被阅读0次
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
 
namespace mysql事务测试
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                using (MySqlConnection conn = new MySqlConnection("Database=xini2ng;Data Source=127.0.0.1;User Id=root;Password=root;pooling=false;CharSet=utf8"))
                {
                    conn.Open();
                    MySqlTransaction transaction = conn.BeginTransaction();
 
 
                    MySqlCommand cmd = conn.CreateCommand();
                    cmd.Transaction = transaction;
 
                    try
                    {
                        cmd.CommandText = "INSERT INTO tbl_phonenumber VALUES('1','1','2','3')";
                        int x = cmd.ExecuteNonQuery();
                        cmd.CommandText = "INSERT INTO tbl_phonenumber VALUES('1','1','2','4','5')";
                        int y = cmd.ExecuteNonQuery();
                        transaction.Commit();
                    }
                    catch (Exception)
                    {
                        try
                        {
                            transaction.Rollback();
                        }
                        catch (Exception)
                        {
                             
                            throw;
                        }
 
                    }
 
                }
            }
            catch (Exception)
            {
 
                throw;
            }
        }
    }
}

相关文章

网友评论

      本文标题:C#代码实现MySQL事务例子

      本文链接:https://www.haomeiwen.com/subject/nagvsxtx.html