When we use C # programming, we often encounter the place to manipulate the database, and if we don't notice, the code that might be written is the following
A text box is defined in the foreground, and the name value is Btnname; A query button is defined with a name value of Btnsearch,click event btnSearch_Click,
Private void btnsearch_click (object sender, routedeventargs e) { using (Sqlconnection conn = new sqlconnection ("data source=.\\ Instance name;initial Catalog=school; persist security info=true; user id=sa; password= password ")) { conn. Open (); using (Sqlcommand cmd = conn. CreateCommand ()) { cmd.CommandText = "select * from student where stugrade= ' " +btnName.Text+ " ' "; //executes multiple result sets, Use ExecuteReader (); using (Sqldatareader reader = cmd. ExecuteReader ()) { while (reader. Read ()) { &Nbsp; string name = reader. GetString (1); messagebox.show (name); } } } } }
If we enter a text box that is not what we want to query, but a string of 1 ' or ' 1 ' = ' 1 then the query will always return true, then all the data in the database will be burst
Therefore, we will use the @ character method
conn. Open (); using (Sqlcommand cmd = conn. CreateCommand ()) { //cmd. commandtext = "Select * from student where stugrade=" " +btnName.Text+ "'"; cmd. commandtext = "select * from student where [email protected]"; cmd. Parameters.Add (New sqlparameter ("@stugrade", Btnname.text)); //executes multiple result sets, using ExecuteReader (); using ( Sqldatareader reader = cmd. ExecuteReader ()) { while (reader. Read ()) { string name = reader. GetString (1);             &NBsp; messagebox.show ( Name); } } }
This way, you can also use the Insert Delete UPDATE statement
Insert INTO .... VALUES (@stugrade, @age);
Delete .... where [email protected];
How the C # writer action database prevents SQL injection vulnerabilities from occurring