C# – OleDbConnection – ExecuteNonQuery requires an open and available Connection. The connection’s current state is closed

coledbcommandoledbconnection

What am I doing wrong here?

using System.Data;
using System.Data.OleDb;

namespace myProject.Account
{
    public class DbManager
    {

        private OleDbConnection OpenDbConnection()
        {
            string connectionString = GetConnectionString();
            return new OleDbConnection {ConnectionString = connectionString};
        }

        private string GetConnectionString()
        {
            return "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\myDataBase.accdb";
        }

       public void InsertUser(string name, string loginName, string password)
       {
            OleDbConnection conn = OpenDbConnection();

            OleDbCommand command = new OleDbCommand(
                 "INSERT INTO tblUser (UserName, LoginName, Password) VALUES (@name,@login,@pwd)",
                 Conn);

            command.Parameters.Add("@name", OleDbType.VarChar).Value = name;
            command.Parameters.Add("@login", OleDbType.VarChar).Value = loginName;
            command.Parameters.Add("@pwd", OleDbType.VarChar).Value = password;
            command.ExecuteNonQuery();
       }
   }
}

.

I got this error:

ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more
information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: ExecuteNonQuery requires an open and available Connection. The connection's current state is closed.

Source Error:

Line 31: command.ExecuteNonQuery();

I have tried to look at some other threads but none have helped:

ExecuteNonQuery requires an open and available Connection. The connection's current state is closed

MS Access DB doesnt save changes after execution (C#)

Best Answer

You appear to be forgetting to open your connection (and are assigning the wrong connection to the command). Try:

       using(OleDbConnection conn = OpenDbConnection())
        {
          using(OleDbCommand command = new OleDbCommand( 
               "INSERT INTO tblUser (UserName, LoginName, Password) VALUES (@name,@login,@pwd)")) 
          {
          command.CommandType = CommandType.Text;
          command.Parameters.Add("@name", OleDbType.VarChar).Value = name; 
          command.Parameters.Add("@login", OleDbType.VarChar).Value = loginName; 
          command.Parameters.Add("@pwd", OleDbType.VarChar).Value = password; 
          command.Connection = conn; 

          conn.Open();

          command.ExecuteNonQuery();
          } 
        }

Instead. I'd recommend using the using statement, too. It will manage your connection.close for you.

Related Topic