Related knowledge:
- The single quotation mark is replaced by two single quotes, although it can play a certain role in preventing SQL injection attack, but the more effective way is to make the content to be spliced into "parameters"
- The
- SqlCommand supports queries with parameters, that is, you can specify parameters in a query statement:
- parameter settings:
string strcmd = " select AccountID from Account WHERE [email protected] and [email protected]
;
For SQL Server databases, "@" is the prefix for the parameter. Two parameters are defined in the previous sentence: @AccountName, @password.
- Assign a value to the parameter before executing the command:
SqlCommand cmd = new SqlCommand (STRCMD, conn); Cmd. Parameters.addwithvalue ( @ AccountName , UserName); Cmd. Parameters.addwithvalue ( @password , password); Cmd.
ExecuteReader ();
- As you can see, the parameters in SQL are the same as the parameters in the usual function, declared first, and then assigned values. When a SQL name is executed, the parameter value is treated as a string as a whole, even if the parameter value contains a single quotation mark, the single quotation mark is treated as a single quote character instead of the beginning and end character of the string. This eliminates the condition of the SQL injection attack in some way.
code example:
1 Static voidMain (string[] args)2 {3 stringUserName ="Joe";4 stringPassword ="123456";5 6 stringstrconn =@"Server=joe-pc;database=accountdbforsqlinjection;uid=sa;pwd=root";7SqlConnection conn =NewSqlConnection (strconn);8 9 stringStrcmd ="SELECT AccountID from account WHERE [email protected] and [email protected]";TenSqlCommand cmd =NewSqlCommand (STRCMD, conn); One ACmd. Parameters.addwithvalue ("@AccountName", userName); -Cmd. Parameters.addwithvalue ("@password", password); - the Try - { - Conn. Open (); -SqlDataReader dr =cmd. ExecuteReader (); + if(Dr. Read ()) - { +Console.WriteLine ("Success"); A } at Else - { -Console.WriteLine ("failed"); - } - } - Catch(Exception e) in { - Console.WriteLine (e); to } + finally - { the Conn. Close (); * } $}
Ado. NET QuickStart--queries with parameters to prevent SQL injection attacks