相关知识:
代码示例:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Data; 7 using System.Data.SqlClient; 8 9 namespace Consoleapplication1310 {11 class PRogram12 {13 static string strConn = @"server=Joe-PC;database=AccountDBforSQLInjection;uid=sa;pwd=root";14 static SqlConnection conn = new SqlConnection(strConn);15 16 static string sql1 = "INSERT INTO Account(AccountID,AccountName,passWord) VALUES"17 + "(100,'sql1','123456')";//此命令正确18 static string sql2 = "INSERT INTO Account(AccountID,AccountName1,password) VALUES"19 + "(100,'sql2','123456')";//此命令因有拼写错误将会失败20 21 static SqlCommand cmd1 = new SqlCommand(sql1, conn);22 static SqlCommand cmd2 = new SqlCommand(sql2, conn);23 24 static void Main(string[] args)25 {26 //OperationWithoutTransaction();27 OperationWithTransaction();28 }29 30 static void OperationWithoutTransaction()31 {32 conn.Open();33 34 try35 {36 cmd1.ExecuteNonQuery();37 cmd2.ExecuteNonQuery();38 }39 catch (Exception e)40 {41 Console.WriteLine("执行失败。");42 Console.WriteLine(e);43 }44 finally45 {46 conn.Close();47 }48 }49 50 static void OperationWithTransaction()51 {52 conn.Open();53 //连接打开后,才能启动事务54 SqlTransaction trans = conn.BeginTransaction();55 //将两个操作添加到同一个事务中56 cmd1.Transaction = trans;57 cmd2.Transaction = trans;58 59 try60 {61 cmd1.ExecuteNonQuery();62 cmd2.ExecuteNonQuery();63 //如果没有出现异常,则提交事务64 trans.Commit();65 }66 catch (Exception e)67 {68 Console.WriteLine("执行失败,事务回滚。");69 Console.WriteLine(e);70 //执行回滚71 trans.Rollback();72 }73 finally74 {75 conn.Close();76 }77 }78 }79 }
程序分析:
新闻热点
疑难解答
图片精选