User login:
, create a login form
connect to SQL Server;
The construction of the SqlCommand class is used to create a SqlCommand object for executing specific SQL statements, such as modifications, updates, deletions, and so on. The steps are as follows:
1. Create the SqlCommand object:
SqlCommand sqlcommand=new SqlCommand ();
2, will SqlCommand. Connection The SqlConnection created on the connection:
SQLCommand. Connection = sqlConnection;
3. define the SQL statement, specify the command text of the SQL command, and the command text is composed of string concatenation:
Sqlcommand.commandtext =? "Select COUNT (1) from Tb_user"
+ "WHERE no= '" + this.txb_UserNo.Text.Trim () + "'"
+ "and password=hashbytes (' MD5 ', '" + this.txb_Password.Text.Trim () + "');";
"+ This.txb_UserNo.Text.Trim () +" is the text box to clear the text after the end of the space, stitching into the command text, " because the text content is a character type, so add single quotation marks.
4, using SqlConnection ExecuteScalar method to indicate whether the user name and password is correct. EXECUTESCALR: Executes the query and returns the value of the first column in the first row of the result, which is of type object. Open the connection and define an integer variable, rowcount, to hold the value of the object type cast. int rowCount = (int) sqlcommand.executescalar (); if rowcount=1, the login succeeds, if 0, the user does not exist and the login fails. The integration code is as follows:Parameters:with"Select COUNT (1) from Tb_user"+ "WHERE no= '" + this.txb_UserNo.Text.Trim () + "'"+ "and password=hashbytes (' MD5 ', '" + this.txb_Password.Text.Trim () + "');";passwords may be tampered with. use parameters to resolve the problem and change the SQL statement to:"Select COUNT (1) from Tb_user WHERE [email protected] and password=hashbytes (' MD5 ', @Password);";Note: Specify the command text for the SQL command, and the command text contains the parameters;sqlCommand.Parameters.AddWithValue ("@No", This.txb_UserNo.Text.Trim ()); sqlCommand.Parameters.AddWithValue ("@Password", This.txb_Password.Text.Trim ());Note: Add the name, value of the parameter to the parameter collection of the SQL command, sqlcommand.parameters["@Password"]. SqlDbType = SqlDbType.VarChar; Note: Set the type of the password parameter to a variable-length string;
Logging in to SQL Server and parameters