开发者

Optimize this code without using distributed transaction

开发者 https://www.devze.com 2023-02-26 10:34 出处:网络
Is there a way this code may be more optimized then it is right now without using TransactionScope ? public static bool DeleteItem(int cusID)

Is there a way this code may be more optimized then it is right now without using TransactionScope ?

public static bool DeleteItem(int cusID)
    {
        int result = 0;

        using (OleDbConnection myConnection = new OleDbConnection(AppConfiguration.ConnectionString))
        {
            string delOrders= "DELETE FROM ORDERS WHERE cusID=?";
            string delCustomer= "DELETE FROM CUSTOMERS WHERE cusID=?";
            OleDbCommand myCommand = null;
            OleDbTransaction tran = null;

            try
            {
                myConnection.Open();
                tran=myConnection.BeginTransaction();


                using (myCommand = new OleDbCommand(delOrder开发者_C百科s, myConnection))
                {
                    myCommand.Parameters.Add("cusID", cusID);
                    myCommand.Transaction = tran;
                    myCommand.ExecuteNonQuery();
                }

                using (myCommand = new OleDbCommand(delCompany, myConnection))
                {
                    myCommand.Parameters.Add("cusID", cusID);
                    myCommand.Transaction = tran;
                    myCommand.ExecuteNonQuery();
                }
                tran.Commit();
                result = 1;
            }

            catch (OleDbException ex)
            {
                tran.Rollback();
                throw ex;
            }

            finally
            {
                myConnection.Close();
            }
        }
        return (result>0);
    }


Why would you want to avoid Transactions if the database is supposed to be consistent while deleting records? Removing transactions here would essentially have probability to bring the database to inconsistent form.

If you just want to remove it from Code, then probably you may want to try out Transactions inside a single Stored Proc. Here are some examples

http://www.codeproject.com/KB/database/sqlservertransactions.aspx

http://msdn.microsoft.com/en-us/library/ms188929.aspx


Just a tip - You can use bool result instead of int result cause function returns bool anyway.

0

精彩评论

暂无评论...
验证码 换一张
取 消