- 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"
- SqlCommand supports queries with parameters, that is, you can specify parameters in a query statement:
- Setting of parameters:
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.
- To assign a value to a 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 void Main (string[] args) 2 {3 String userName = "Joe"; 4 string Passwor D = "123456"; 5 6 String strconn = @ "Server=joe-pc;database=accountdbforsqlinjection;uid=sa;pwd=root"; 7 SqlConnection conn = new SqlConnection (strconn); 8 9 String strcmd = "Select AccountID from Account WHERE [email protected] and [email protected]"; 1 0 SqlCommand cmd = new SqlCommand (STRCMD, conn); Parameters.addwithvalue ("@AccountName", userName); Parameters.addwithvalue ("@password", password), TRY16 {conn. Open (); SqlDataReader dr = cmd. ExecuteReader (), if (Dr. Read ()) {Console.WriteLine ("Success");}23 Else24 {Console.WriteLine ("failure"); 26}27}28 catch (Exception e) {Console.WriteLine (e);}32 Finally3 3 {Conn. Close (); 35}36}
Query with parameters to prevent SQL injection attacks