一段连接Sql的登录界面代码,总是弹出用户名密码错误
程序代码:
private void btnLogin_Click(object sender, EventArgs e) { if (this.txtUserName.Text.Trim() == "") { MessageBox.Show("用户名不能为空", "提示"); return; } //连接字符串 string str = "server=localhost;database=addressBook;uid=sa;pwd=123456"; //连接对象 SqlConnection con = new SqlConnection(); con.ConnectionString = str; //打开数据库 con.Open(); //执行命令 // cmd.Connection = con; DataSet ds = new DataSet(); String st = "select User,Password from users where User='"+txtUserName.Text.ToString().Trim()+"' and PassWord='"+txtPassword.Text.ToString().Trim()+"'"; SqlCommand cmd = new SqlCommand(st, con); SqlDataReader dr = cmd.ExecuteReader(); try { if (dr.Read()) { this.Hide(); MainForm frm = new MainForm(); frm.Show(); } else { MessageBox.Show("账号和密码错误,请重新输入!", "提示"); txtPassword.Text = ""; this.Focus(); } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { cmd.Dispose(); con.Dispose(); } }