Circumvent SQL injection
If you do not evade, in the black window in the input content with the use of splicing statements can attack the data
Example: Enter code value
P001 ' Union SELECT * from Info where ' 1 ' = ' 1//This can query all data, do not easily trust the user input content
Preventing SQL injection attacks
General method: You can match the special symbol with regular
Recommended method : Send an SQL statement to the command two times
Split the SQL statement into two blocks
The user enters a piece;
For the first time, the SQL statements written in the CommandText are sent past; the second time the value of the variable is sent past, matching
Cases:
Make the column name equal to a variable name
Change the amount of binding parameter cmd. Parameters.addwithvalue ("Variable name", variable value);
Cmd. Parameters is a property within an object, and the return value is a collection
Sometimes the same variable name is used, so remove the cmd before binding the parameter . Parameters.clear ();
Static voidMain (string[] args) { //receiving query criteria entered by the userConsole.WriteLine ("Please enter the vehicle code to be queried:"); stringCode =Console.ReadLine (); //Connecting ObjectsSqlConnection conn =NewSqlConnection ("server=.; Database=mydb;user=sa;pwd=123"); //Create Command ObjectSqlCommand cmd =Conn. CreateCommand (); //an SQL statement to the command object//make code= a variableCmd.commandtext ="SELECT * from Car where [email protected]"; //cmd.commandtext = "SELECT * from Car where [email protected] or [email protected]"; //change the amount of binding parametersCmd. Parameters.clear ();//to clear a bound variable, it is best to write a purge before using the parameter collectionCmd. Parameters.addwithvalue ("@code", code); //cmd. Parameters.addwithvalue ("@name", name);//How many columns are tied?//Open ConnectionConn. Open (); //Execute SQL statementSqlDataReader dr =cmd. ExecuteReader (); //reading Data if(Dr. HasRows) { while(Dr. Read ()) {Console.WriteLine (dr[0] +"--"+ dr[1]); } } Else{Console.WriteLine ("no corresponding data was found."); } //Close ConnectionConn. Close (); Console.ReadLine (); }
View Code
ADO to prevent SQL string injection attacks