错误:连接未关闭,连接的当前状态为打开

本文关键字:连接 状态 错误 | 更新日期: 2023-09-27 18:34:50

我不知道我的错误在哪里......我已经把connection.close((放在任何地方了。 我在Microsoft Visual Studio 2013 C#中使用Access数据库。 它在没有数据库的情况下运行良好,但是当我尝试向其添加数据库时,这就是问题开始发生的地方。

private void btnLogin_Click(object sender, EventArgs e)
    {
        connection.Open();
        OleDbCommand command = new OleDbCommand();
        command.Connection = connection;
        command.CommandText = "SELECT * from Login where [Username]='" + txtUser.Text + "' and [Password]='" + txtPass.Text + "' ";
        OleDbDataReader reader = command.ExecuteReader();
        int count = 0;
        while (reader.Read())
        { 
            count = count + 1;
        }
        if (count == 1)
        {
            connection.Open();
            Form main = new AdminMain();
            main.Show();
            this.Hide();
            try
            {
                connection.Open();
                command.Connection = connection;
                command.CommandText = "INSERT into LogHisto ([Username],[LogDate],[LogTime]) values ('" + txtUser.Text + "','" + dateTimePicker1.Text + "','" + dateTimePicker2.Text + "')";
                command.ExecuteNonQuery();
                connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error" + ex);
            }
            connection.Close();
        }
        else
        {
            MessageBox.Show("Username/Password is incorrect");
            try
            {
                connection.Open();
                command.Connection = connection;
                command.CommandText = "INSERT into LogHisto (Username,LogDate,LogTime) values ('" + txtUser.Text + "','" + dateTimePicker1.Text + "','" + dateTimePicker2.Text + "')";
                command.ExecuteNonQuery();
                connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error" + ex);
            }
        }
        connection.Close();
    }

错误:连接未关闭,连接的当前状态为打开

    if (count == 1)
    {
        connection.Open(); // <-------------FIRST TIME
        Form main = new AdminMain();
        main.Show();
        this.Hide();
        try
        {
            connection.Open();// <-------------SECOND TIME
            command.Connection = connection;
            command.CommandText = "INSERT into LogHisto ([Username],[LogDate],[LogTime]) values ('" + txtUser.Text + "','" + dateTimePicker1.Text + "','" + dateTimePicker2.Text + "')";
            command.ExecuteNonQuery();
            connection.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error" + ex);
        }
        connection.Close();
    }

在此代码块中,您将打开同一连接两次,因此您有此异常。只需删除其中一个connection.Open();您还需要删除其中一个connection.Close();

此外,您应该在查询中使用参数!这将防止 sql 注入。我建议你为DataAccess做不同的课程。这将防止此类错误。