gpt4 book ai didi

c# - 阅读器关闭时读取的尝试无效。 C# 数据库

转载 作者:行者123 更新时间:2023-11-30 22:52:30 26 4
gpt4 key购买 nike

此脚本位于我的 visual basic 应用程序的注册页面上。只有当我关闭应用程序时,脚本才会将数据保存在数据库中而没有错误,它会在阅读器关闭时给我错误的无效尝试读取。这只发生在这个页面上

 if (PasswordRegister.Text == RepeatPasswordRegister.Text)
{

if (PasswordRegister.Text == "")
{
MessageBox.Show("Enter a vailed password");
}
else if (UsernameRegister.Text == "")
{
MessageBox.Show("Enter a vailed Username");
}
else {

string myConnection = "datasource=127.0.0.1;port=3306;username=root;password=Root;";
MySqlConnection myConn = new MySqlConnection(myConnection);

MySqlCommand Login = new MySqlCommand("select * from database.users where Username='" + this.UsernameRegister.Text + "' ;", myConn);

MySqlDataReader RegisterReader;
myConn.Open();
RegisterReader = Login.ExecuteReader();
int count = 0;
while (RegisterReader.Read())
{
count = count + 1;
}
if (count == 1)
{
MessageBox.Show("Username is taken");
}
else if (count > 1)
{
MessageBox.Show("ERROR Contact support");
}
else {


string constring = "datasource=127.0.0.1;port=3306;username=root;password=Root;";
string Query = "insert into database.users (Username, Password) values ('" + this.UsernameRegister.Text + "','" + this.PasswordRegister.Text + "') ;";
MySqlConnection conDataBase = new MySqlConnection(constring);
MySqlCommand cmdDataBase = new MySqlCommand(Query, conDataBase);
MySqlDataReader myReader;
try
{
conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
MessageBox.Show("Register Succes");
conDataBase.Close();
conDataBase.Dispose();
this.Hide();
Form1 home = new Form1();
home.ShowDialog();
while (myReader.Read())
{

}
}


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

}
myConn.Close();
}
}
else {
MessageBox.Show("Check password");
};

最佳答案

如果仔细查看代码,您会注意到在尝试从阅读器读取之前已关闭连接:

conDataBase.Open();
myReader = cmdDataBase.ExecuteReader();
conDataBase.Close(); *** Connection closed here
conDataBase.Dispose(); *** And disposed disposed, for good measure
...
while (myReader.Read()) *** Now you are trying to Read!
{

}

您需要做的是保持连接打开,直到您完成阅读,例如

using (var myConn = new MySqlConnection(myConnection))
using (var Login = new MySqlCommand("select * from database.users where Username= @myUserName",
myConn);
{
cmdDataBase.AddWithValue(new MySqlParameter("@myUserName", this.UsernameRegister.Text));
conDataBase.Open();
using (var myReader = cmdDataBase.ExecuteReader())
{
while (myReader.Read())
{
// Do something with myReader[] fields here
}
} // Reader disposed
} // Command Disposed, Connection Closed + Disposed

我也更喜欢使用 using 语法来管理连接、命令和阅读器等一次性用品,同时参数化您的查询和命令——这具有安全性,也可能具有性能优势.

关于c# - 阅读器关闭时读取的尝试无效。 C# 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27732206/

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