gpt4 book ai didi

c# - 在创建密码更改表单时出现异常

转载 作者:行者123 更新时间:2023-11-30 15:32:05 25 4
gpt4 key购买 nike

我正在创建密码更改表单。当我执行表单并填写文本框时,它给出一个异常消息 There already and open DataReader associated with this command which must be closed first.

他是我正在使用的代码:

private bool CompareStrings(string string1, string string2)
{
return String.Compare(string1, string2, true, System.Globalization.CultureInfo.InvariantCulture) == 0 ? true : false;
}

private void button1_Click(object sender, EventArgs e)
{
try
{
SqlConnection con1 = new SqlConnection();
con1.ConnectionString = "data source=.;Initial catalog=inventory;Integrated Security=true";
con1.Open();

SqlCommand cmd = new SqlCommand("SELECT ISNULL(username, '') AS username, ISNULL(password,'') AS password FROM login WHERE username='" + textBox1.Text + "' and password='" + textBox2.Text + "'", con1);

SqlDataReader dr = cmd.ExecuteReader();

string userText = textBox1.Text;
string passText = textBox2.Text;

while (dr.Read())
{
if (this.CompareStrings(dr["username"].ToString(), userText) &&
this.CompareStrings(dr["password"].ToString(), passText))
{
SqlCommand cmd2 = new SqlCommand("UPDATE login SET password='" + textBox3.Text + "'where username='" + textBox1.Text + "'", con1);
cmd2.ExecuteNonQuery();
MessageBox.Show("Password Changed Successfully");
}
else
{
MessageBox.Show("Incorrect Old password");
}

}

dr.Close();

con1.Close();

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

最佳答案

您不能在 SqlDataReader 时执行命令在同一连接上打开。您可以执行以下两项操作之一来更改您的代码:

  1. 创建第二个连接并在第二个连接上运行更新查询。

  2. 存储阅读器的数据,关闭阅读器,稍后更新所有数据。在您的情况下,您可以存储所有用户名以使用 Username in (<yourlisthere>) 在一个更新查询中更新和更新它们

关于c# - 在创建密码更改表单时出现异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19644658/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com