2015-02-10 37 views
-1

这里是C#代码在检索密码代码总是返回重试,而不是恢复密码

protected void Button2_Click(object sender, EventArgs e) 
{ 
    SqlConnection conn = new SqlConnection("Data Source=Mrunal;Initial Catalog=JobPortalDB;Integrated Security=True"); 
    conn.Open(); 
    string s1 = "select password from Registration where SecurityQues='" + seqQue.SelectedItem.Text + "' and SecurityAns='" + TextBox2.Text + "' and emailId='" + TextBox1.Text + "'"; 

    SqlCommand cmd = new SqlCommand(s1, conn); 
    SqlDataReader dr; 
    dr = cmd.ExecuteReader(); 

    if (dr.Read()) 
     Label2.Text = dr[0].ToString(); 
    else 
     Label2.Text = "try again"; 
} 

码不显示错误,但它无法正常工作。

如果有人得到更正,请帮忙吗?

在此先感谢

+5

你调试代码,并检查您的变量?什么是_不完全工作?什么是你的专栏类型?您的查询是否返回SSMS中的任何数据?您应该始终使用参数化查询。这种字符串级联对于SQL注入攻击是开放的。并使用using语句来处理你的sql连接和命令。 – 2015-02-10 09:56:53

+0

在db中执行相同的查询并检查它是否真的存在? – 2015-02-10 09:57:39

+0

得到了上述错误。实际上它在secQue字段中存储零,同时从下拉列表中进行选择。感谢导航。但我仍然没有得到,为什么dropdownlist存储零,而不是选择的价值形式dropdownlist – 2015-02-10 10:08:29

回答

2

如果您运行查询并尝试返回行,请尝试使用HasRows。

像这样:

if (dr.HasRows) 
    dr.Read(); 
    Label2.Text = dr[0].ToString(); 
else 
    Label2.Text = "try again"; 
+0

_如果有一行,并且没有下一行可读dr.Read()返回false_我不这么认为。 'SqlDataReader'的默认位置是_before_开始时的第一条记录。这就是为什么,OP_must_调用'Read'来开始访问任何数据。 – 2015-02-10 10:11:02

+0

是的,我混淆了它,它在一行上返回true,而在下一个返回false。 – okisinch 2015-02-10 10:13:20

+0

但在dr.HasRows之前不需要dr.Read()。 – okisinch 2015-02-10 10:19:37

2

尝试用这种

while(dr.Read()) 
{ 
    if (dr.HasRows) 
    { 
    Label2.Text = dr["password"].ToString(); 
    } 
    else 
    { 
    Label2.Text = "try again"; 
    } 
}