//获取用户输入的用户名和密码
string userName=txtuserName.Text.Trim();
string pwd=txtPwd.Text.Trim();
//设置数据库连接
string strCon = "Server=PC-20161029WDCV\\SQL2014;Database=StudentDB;Trusted_Connection=True";
SqlConnection con = new SqlConnection(strCon);
//设置Sql语句,并实现参数化
string sql="select count(*) from Users where UserName=@uName and PassWord=@Pwd";
SqlCommand cmd=new SqlCommand(sql,con);
//SqlParameter实例化,并将参数值进行替换
SqlParameter[] p={new SqlParameter("@uName,userName"),new SqlParameter (“@pwd,pwd”)};
cmd.Parameters.AddRange(p);
//查询数据库
con.open();
int i=(int)cmd.ExecutaScalar();
con.close();
if(i>0)
{
MessageBox.Show("用户名和密码正确!");
}
else
{
MessageBox.Show("用户名和密码错误!");
}