问题描述
protectedvoidbtnEnter_Click(objectsender,EventArgse){stringUserName=this.UserName.Text.Trim();stringPassWord=this.PassWord.Text.Trim();SqlConnectioncon=newSqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);con.Open();Stringstr="select*fromLoginwhereUserName='"+UserName+"'andPassWord='"+PassWord+"'";SqlCommandSqlComm=newSqlCommand(str,con);//SqlComm.CommandText="select*frommyusertablewheretext='"+UserName+"'andpassword='"+PassWord+"'";//"select*fromLoginwhereUserName=@UserNameandPassWord=@PassWord";SqlDataReaderthisReader=SqlComm.ExecuteReader();if(thisReader.Read()){if(thisReader["UserName"].ToString().Trim()==UserName){Response.Write("登录成功");}else{Response.Write("登录失败");}}}
解决方案
解决方案二:
断点跟,应该是报错了,仔细看报的什么错
解决方案三:
andPassWord中and前加个空格。
解决方案四:
if(thisReader.Read())没读到值肯定前面错了
解决方案五:
Web用户登录示例protectedvoidButton1_Click(objectsender,EventArgse)//获取Web.config中配置的数据库连接字符串{stringsqlstr=System.Configuration.ConfigurationManager.AppSettings["con"].ToString();SqlConnectionconn=newSqlConnection(sqlstr);//连接数据库conn.Open();//打开数据库SqlCommandcmd=newSqlCommand();//创建SqlCommand对象cmd.Connection=conn;//设置该对象使用conn连接数据库cmd.CommandType=CommandType.Text;//设置类型cmd.CommandText="selectcount(*)fromTb_LoginwhereUseName='"+txtUserName.Text.Trim()+"'andUsePassword='"+txtPwd.Text.Trim()+"'";//设置sql语句intflag=int.Parse(cmd.ExecuteScalar().ToString());//执行sql语句并获取返回值if(flag>0)//如果大于0{Page.ClientScript.RegisterStartupScript(this.Parent.GetType(),"","alert('登录成功');",true);//说明登陆成功}else{Page.ClientScript.RegisterStartupScript(this.Parent.GetType(),"","alert('登录失败');",true);//否则登陆失败}conn.Close();//关闭连接}
解决方案六:
1.很笨,你没有注册点击事件2.thisReader.Read()判断等于false断点跟下面代码应该有问题。SqlConnectioncon=newSqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString);con.Open();SqlCommandSqlComm=newSqlCommand(str,con);3.整一个事件try-catch看有没有捕获什么异常