[ExecuteReader 要求已打开且可用的 Connection。连接的当前状态为已关闭。请问大佬知道这个是什么原因吗?
源代码如下:
string name = textBox1.Text.Trim();
string password1 = textBox2.Text.Trim();
string password2 = textBox3.Text.Trim();
string Name = textBox4.Text.Trim();
string number = textBox5.Text.Trim();
if (name == “”)
{
MessageBox.Show(“用户名不能为空!”, “登录失败”, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
if (password1 != password2)
{
MessageBox.Show(“两次输入的密码不一致!”, “登录失败”, MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
SqlConnection con = new SqlConnection();
con.ConnectionString = “Data source=(local);Initial Catalog=Management;Integrated Security=True”;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select username from manager";
cmd.Connection = con;
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
string username = reader["username"].ToString();
if (name == username)
{
MessageBox.Show("用户名已存在!", "注册失败", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
string sql = "insert into manager(username,pwd,name,ID)values(" + name + "," + password1 + "," + Name + "," + number + ")";
try
{
SqlCommand comm = new SqlCommand(sql, con);
int count = comm.ExecuteNonQuery();
if (count >= 0)
{
MessageBox.Show("注册成功,请前往登录", "注册成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
MessageBox.Show("注册失败", "注册失败", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "数据库出错!", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally
{
con.Close();
}
Form1 a = new Form1();
a.Show();
this.Visible=false;
}
}
}
}