When creating a login form, if you do not pay attention to it, it is very likely that there is a problem in writing code. When designing a login form, beginners prefer to use this method for login design.
String sqlcon = "data source =. \ sqlexpress; database = MyCy; uid = sa; pwd = 123456 ;"
String SQL = "select * from tb_user where username = '" + txtuser. text + "' and userpwd = '" + txtpwd. text + "'";
SqlCommand cmd = new SqlCommand (SQL, sqlcon );
In this way, when you enter single quotes or other characters, for example, when txtpwd is 1 'or '1' = '1, in this case, SQL = select * from tb_user where username = "username" and userpwd = '1' or '1' = '1'. At this time, it is obviously consistent, in this case, SqlParameter is used to prevent injection attacks.
The detailed design process of the logon form is as follows:
Add the following code under the click event of btnOK
String sqlcon = "data source =. \ sqlexpress; database = MyCy; uid = sa; pwd = 123456 ;"
SqlConnection sqlcon = new SqlConnection (sqlcon );
If (sqlcon. State = ConnectionState. Closed)
Sqlcon. Open ();
String SQL = "select username, userpwd from tb_user where username = @ username and userpwd = @ userpwd ";
Try
{
SqlParameter [] parms = new SqlParameter [2];
Parms [0] = new SqlParameter ("@ username", SqlDbType. VarChar, 50 );
Parms [0]. Value = txtUser. Text;
Parms [1] = new SqlParameter ("@ userpwd", SqlDbType. VarChar, 50 );
Parms [1]. Value = txtPwd. Text;
SqlCommand cmd = new SqlCommand (SQL, sqlcon );
Cmd. Parameters. AddRange (parms );
Using (SqlDataReader dr = cmd. ExecuteReader ())
{
Dr. Read ();
If (dr. HasRows)
{
MainForm mainForm = new MainForm ();
DialogResult = DialogResult. OK; // used when LoginForm is disabled after the logon form is successfully set.
}
Else
{
MessageBox. Show ("incorrect user name and password! ");
}
}
Sqlcon. Close ();
}
Catch (Exception ex)
{
MessageBox. Show (ex. Message );
}
This prevents the above error. When the user inputs 1 'or '1' = '1, 1' or '1' = '1 as a whole for verification, the SQL statement is parsed as follows: SQL = select * from tb_user where username = "username" and userpwd = 1 'or '1' = '1, prompting that the user password is incorrect, achieve the purpose of prevention.
By the way, to close the logon form after successful logon, add the following code to the Main () entry point function of Program:
LoginForm login = new LoginForm ();
If (login. ShowDialog () = DialogResult. OK)
Application. Run (new MainForm (); to close the logon form.