【发布时间】:2018-06-06 08:52:49
【问题描述】:
我正在使用 C# Form 和 SQL Server。登录时遇到问题。
"System.InvalidOperationException: '连接未关闭'。
我无法解决这个问题。我想我添加了很多“con.Open()”。但我尝试了很多方法,但我仍然接受这个错误。猜猜,我又删了一个开关,是真的吗?
private void buttonLogin_Click(object sender, EventArgs e)
{
con.Open();
if (String.IsNullOrEmpty(textBoxUserName.Text))
{
MessageBox.Show("Username can't be empty");
textBoxUserName.Focus();
con.Close();
}
if (String.IsNullOrEmpty(textBoxPassword.Text))
{
MessageBox.Show("Password can't be empty");
textBoxPassword.Focus();
con.Close();
}
else
{
con.Open();
SqlCommand SelectCommand = new SqlCommand("SELECT * FROM Users WHERE username ='" + textBoxUserName.Text.Trim() + "' and password= '" + textBoxPassword.Text.Trim() + "'");
SqlDataReader myReader;
myReader = SelectCommand.ExecuteReader();
int count = 0;
string userRole = string.Empty;
while (myReader.Read())
{
count = count + 1;
userRole = myReader["userrank"].ToString();
}
if (count == 1)
{
if (userRole =="admin" )
{
Form1 form = new Form1();
this.Hide();
form.Show();
con.Close();
}
else
{
UI ui = new UI();
this.Hide();
ui.Show();
con.Close();
}
myReader.Close();
}
else
{
MessageBox.Show("Check your username or password");
con.Close();
}
}
}
【问题讨论】:
-
解决方案:不要重复使用你的连接,但总是在你使用它的地方打开和关闭它(在方法中),最好使用
using-statement 来确保它总是被处理/关闭. -
您应该使用
using,并且您应该在尽可能小的范围内创建(并处置)一个连接,而不是重用con对象。SqlConnection实例只是句柄,而不是物理连接,您可以打开和关闭它们几乎没有任何资源成本。重用它们只会给你带来麻烦——首先,你如何处理断开的连接? (答案是:非常尴尬,如果你只有一个实例。) -
我看不懂
Form1 form = new Form1();和UI ui = new UI();行。 -
你被这么多的打开/关闭弄糊涂了。为什么在进行正常验证时还要费心打开?始终使用
using,以便您始终确定。 -
@SeM 如果管理员要登录,请通过 Form1 或用户要登录 UI。
标签: c# sql sql-server winforms