如何在C#中使用事务 [英] How can I use transactions in C#

查看:118
本文介绍了如何在C#中使用事务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

HI,我编写了一个简单的查询,从db中选择数据,并将数据插入到不同的表中。我必须在这里使用事务,如果任何一个查询无法执行,那么它们应该执行。有人可以帮我解决一下这个问题。



我尝试了什么:



I had written a simple query that selects the data from db, and that data i am inserting into different tables. I have to use transactions here, if any one query failed to execute non of them should execute. Can some one please help me out how can i do this.

What I have tried:

DataTable dtInsertData = new DataTable();
try
{
   dLib = new DataLibrary("VillageMate", false);
   dtInsertData = dLib.GetDataTable("SELECT * FROM VillageMate_ESS  where LogID=(select  max(LogID) from [VillageMate_ESS])");
   if (dtInsertData.Rows.Count>0)
   {
     dLib = new DataLibrary("ESS", false);

     sqlQUERY =   "INSERT INTO  [MSTR_Employee] (FirstName, NationalID, EmployeeCode,CreatedDateTime,RecordStatus) VALUES ('"+dtInsertData.Rows[0]["Name"].ToString() + " ' , '" + dtInsertData.Rows[0]["IDNumber"].ToString() + "' , '" + dtInsertData.Rows[0]["RFID"].ToString()+"' , '"+DateTime.Now.ToString()+"' , '"+true+"')";

    sqlQUERY += "INSERT INTO  [MSTR_Employee_Optional] (TNAEnrollID, CreatedDateTime,RecordStatus) VALUES ('" + dtInsertData.Rows[0]["RFID"].ToString() + "' , '" + DateTime.Now.ToString() + "' , '" + true + "')";

    sqlQUERY+= "INSERT INTO  [ACS_Card] (CardNumber, StartDate,EndDate, GUIDCard, CreatedDateTime,RecordStatus) VALUES ('" + dtInsertData.Rows[0]["IDNumber"].ToString() +
                            " ' , '" + dtInsertData.Rows[0]["ValidFromDate"].ToString() + "' , '" + dtInsertData.Rows[0]["ValidToDate"].ToString() + "' ,'" + dtInsertData.Rows[0]["RFID"].ToString() + "', '" + DateTime.Now.ToString() + "' , '" + true + "')";

                   sqlQUERY+= "INSERT INTO  [ACS_CardOption] (IsVisitorCard,IsGuardCard, TraceAccess, CreatedDateTime,RecordStatus) VALUES ('" + true +
                            " ' , '" + false + "' , '" + false + "' , '" + DateTime.Now.ToString() + "' , '" + true + "')";

       sqlQUERY+= "INSERT INTO  [ACS_CardStatus] (CardStatus, CreatedDateTime,RecordStatus) VALUES ('" + 5 +
                            " ' , '" + DateTime.Now.ToString() + "' , '" + true + "')";

       sqlQUERY+="INSERT INTO  [ACS_ActivityTransaction] (ActivityStatus, ActivityFailCount,ActivitySource, CreatedDateTime,RecordStatus) VALUES ('" + true +
                            " ' , '"+0+"' , '"+0+"' , '" + DateTime.Now.ToString() + "' , '" + true + "')";

      int status = dLib.ExecuteNonQuery(sqlQUERY);
     }
        return dtInsertData;
   }
   catch (Exception ee)
   {
      WriteLogs.WriteErrorLogs(-1, 0, GetType().FullName + "." + MethodBase.GetCurrentMethod().Name, ee.ToString());
      return null;
   }

推荐答案

 sqlQUERY =   "INSERT INTO  [MSTR_Employee] (FirstName, NationalID, EmployeeCode,CreatedDateTime,RecordStatus) VALUES ('"+dtInsertData.Rows[0]["Name"].ToString() + " ' , '" + dtInsertData.Rows[0]["IDNumber"].ToString() + "' , '" + dtInsertData.Rows[0]["RFID"].ToString()+"' , '"+DateTime.Now.ToString()+"' , '"+true+"')";

sqlQUERY += "INSERT INTO  [MSTR_Employee_Optional] (TNAEnrollID, CreatedDateTime,RecordStatus) VALUES ('" + dtInsertData.Rows[0]["RFID"].ToString() + "' , '" + DateTime.Now.ToString() + "' , '" + true + "')";



不是你问题的解决方案,而是你遇到的另一个问题。

永远不要通过连接字符串来构建SQL查询。迟早,您将使用用户输入来执行此操作,这会打开一个名为SQL注入的漏洞,这对您的数据库很容易并且容易出错。

名称中的单引号你的程序崩溃。如果用户输入像Brian O'Conner这样的名称可能会使您的应用程序崩溃,那么这是一个SQL注入漏洞,崩溃是最少的问题,恶意用户输入,并且它被提升为具有所有凭据的SQL命令。

SQL注入 - 维基百科 [ ^ ]

SQL注入 [ ^ ]

按示例进行SQL注入攻击 [ ^ ]

PHP:SQL注入 - 手册 [ ^ ]

SQL注入预防备忘单 - OWASP [ ^ ]

我该怎么办?解释没有技术术语的SQL注入? - 信息安全堆栈交换 [ ^ ]


Not a solution to your question, but another problem you have.
Never build an SQL query by concatenating strings. Sooner or later, you will do it with user inputs, and this opens door to a vulnerability named "SQL injection", it is dangerous for your database and error prone.
A single quote in a name and your program crash. If a user input a name like "Brian O'Conner" can crash your app, it is an SQL injection vulnerability, and the crash is the least of the problems, a malicious user input and it is promoted to SQL commands with all credentials.
SQL injection - Wikipedia[^]
SQL Injection[^]
SQL Injection Attacks by Example[^]
PHP: SQL Injection - Manual[^]
SQL Injection Prevention Cheat Sheet - OWASP[^]
How can I explain SQL injection without technical jargon? - Information Security Stack Exchange[^]


首先,谷歌针对SQL注入攻击找出你写的查询为什么不好。您还调试代码要困难得多。例如,如果这些字段中的任何一个字段中包含字符,该怎么办?您的查询失败了,或者更糟。



接下来,谷歌搜索C#参数化查询以了解如何处理,并使您的代码更易于调试和维护在这个过程中。



现在你可以继续进行交易了。您可以使用轻松完成此操作TransactionScope [ ^ ]。
First, Google for "SQL Injection Attack" to find out why the queries you've written are do bad. You also made debugging that code far more difficult. For example, what if any single one of those fields has a ' character in it? Your query just failed, or worse.

Next, Google for "C# parameterized queries" to find out what to do about, and make your code easier to debug and maintain in the process.

Now you can move on to transactions. You can do it quite easily with a TransactionScope[^].


我的建议是获取所有查询并将它们放在存储过程中。除了较少的代码复杂性和网络闲聊之外,原始查询没有参数,因此不存在SQL注入漏洞。
My recommendation would be to take all of the queries and place them inside of a stored procedure. Besides less code complexity and network chit-chat, the original query has no parameters so there would be no SQL Injection vulnerability.


这篇关于如何在C#中使用事务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆