create a transaction for MS Access in c#

后端 未结 2 1757
無奈伤痛
無奈伤痛 2020-12-22 02:47

I need some code in my c# application to implement a transaction using Microsoft Access database

相关标签:
2条回答
  • 2020-12-22 02:57

    OleDbTransaction class is made just for that. You can create one by calling BeginTransaction on your OleDbConnection object then Commit or Rollback up to your scenario

    using (var transaction = cn.BeginTransaction()) {
      //Do Stuff here using the connection
      transaction.Commit();
    }
    

    The transaction will be rolled back at dispose if no commit has been called.

    0 讨论(0)
  • 2020-12-22 02:58

    Try to implement the code similar to the one below.

        public void InsertPersonAndPhoneNumber(int personId, string name, string phone)
        {
            string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=./contacts.accdb";
            OleDbConnection cn = new OleDbConnection(connectionString);
            try
            {
                cn.Open();
                OleDbTransaction trans = cn.BeginTransaction();
                try
                {
                    //first transaction ...
                    string sql1 = "INSERT INTO People (ID, pname) VALUES (@ID, @pname)";
                    OleDbCommand cmd1 = new OleDbCommand(sql1, cn, trans);
                    cmd1.Parameters.AddWithValue("@ID", personId);
                    cmd1.Parameters.AddWithValue("@pname", name);
                    cmd1.ExecuteNonQuery();
    
                    //first transaction ...
                    string sql2 = "INSERT INTO PhoneNumbers (PID, num) VALUES (@PID, @num)";
                    OleDbCommand cmd2 = new OleDbCommand(sql2, cn, trans);
                    cmd2.Parameters.AddWithValue("@PID", personId);
                    cmd2.Parameters.AddWithValue("@num", phone);
                    cmd2.ExecuteNonQuery();
    
                    trans.Commit();
                    Console.WriteLine("New Contact Added successfully ...");
    
                }
                catch (Exception x)
                {
                    //handle exception .... 
                    trans.Rollback();
                    Console.WriteLine(x.Message);
                }
                finally
                {
                    cn.Close();
                }
            }
            catch (Exception x)
            {
                //handle exception .... 
    
            }
    
        }
    
    0 讨论(0)
提交回复
热议问题