代码如下
private void btn_login_Click(object sender, EventArgs e){SqlConnection sqlconnection = new SqlConnection();sqlconnection.ConnectionString = ConfigurationManager.ConnectionStrings["SQL"].ConnectionString;SqlCommand sqlcommand = new SqlCommand();sqlcommand.Connection = sqlconnection;sqlcommand.CommandText = "select COUNT(1) from tb_stuinfo where name=@name and pwd=@pwd "; //'"+txt_number.Text+"'and pwd= HASHBYTES('md5','"+txt_pwd.Text+"')";sqlcommand.Parameters.AddWithValue("@name",txt_number.Text.Trim());sqlcommand.Parameters.AddWithValue("@pwd", txt_pwd.Text.Trim());sqlconnection.Open();int rowCount = (int)sqlcommand.ExecuteScalar();sqlconnection.Close();if (rowCount == 1){MessageBox.Show("登陆成功");}else{MessageBox.Show("错误");this.txt_pwd.Focus();this.txt_pwd.SelectAll();}}
问题1
在登录窗体的代码中 若sql语句中使用了”+this.txt_number+”会导致数据类型不符合,登陆失败;改为”+txt_number.text+”,就能解决
注册
private void btn_regest_Click(object sender, EventArgs e){if (txt_number.Text == "" && txt_pwd.Text == ""){MessageBox.Show("用户名或密码不能为空");}SqlConnection sqlconnection = new SqlConnection();sqlconnection.ConnectionString = ConfigurationManager.ConnectionStrings["SQL"].ConnectionString;SqlCommand sqlcommand = new SqlCommand();sqlcommand.Connection = sqlconnection;sqlcommand.CommandText = "insert tb_stuinfo (name,pwd) values(@name,HASHBYTES('MD5',@pwd))";sqlcommand.Parameters.AddWithValue("@name", txt_number.Text.Trim());sqlcommand.Parameters.AddWithValue("@pwd", txt_pwd.Text.Trim());sqlcommand.Parameters["@pwd"].SqlDbType=SqlDbType.VarChar;sqlconnection.Open();int rowAffected = sqlcommand.ExecuteNonQuery();sqlconnection.Close();if (rowAffected == 1){MessageBox.Show("ok");//frm_login lg = new frm_login();//lg.ShowDialog();}else{MessageBox.Show("wrong");}}