Data
Data

Reputation: 113

Adding records to MS Access database through C#

I am attempting to add items to an Access database in C#. I have code that seems to work (I can open and close a database), but the button click event produces errors. I have been searching on Google for the whole afternoon but no joy. My code is:

private void button26_Click(object sender, EventArgs e)
{  //Setup tab LoadDatabase
try
{
connection.Open();
button26.ForeColor = Color.Lime;
mainDataGridView.Visible = true;
OleDbCommand cmd = new OleDbCommand();
cmd.CommandText = "INSERT INTO Main('Prop', 'Value',   'Default','Type')    VALUES('one', 'Kelly', 'Jill','one')";
cmd.ExecuteNonQuery();
button26.Text = "Done Insert"; 
connection.Close();
}
catch (Exception ex)
{
richTextBox1.Text=("Error "+ex);
button26.ForeColor = Color.Black;
connection.Close();
}
}

And the error I get is:

Error System.InvalidOperationException: ExecuteNonQuery: Connection property has not been initialized.
at System.Data.OleDb.OleDbCommand.ValidateConnection(String method)
at System.Data.OleDb.OleDbCommand.ValidateConnectionAndTransaction(String method)
? at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
at CrewCheifSettingsBeta3.Form1.button26_Click(Object sender, EventArgs e) in C:\Somepath\Form1.cs:line 49

Clearly something wrong with the connection string, and that it's not SQL-injection proof either.

Upvotes: 0

Views: 75

Answers (3)

Steve
Steve

Reputation: 216363

The problem is well known. A command need to know the connection to use to execute the command text. However you have other problems in your code.

Connection objects (like commands) should not be global, but created when they are needed and destroyed after. The using statement is very usefull here because you don't have to explicitly close and destroy these objects and you will never have resource leaks when an exception occurs.

Second, when you use field names that are also reserved keywords in your database you should enclose these name in some kind of escape characters. These characters for Access are the open/close brackets not the single quote.

private void button26_Click(object sender, EventArgs e)
{  
    try
    {
        string cmdText = @"INSERT INTO Main
                          ([Prop], [Value], [Default],[Type])    
                          VALUES('one', 'Kelly', 'Jill','one')";
        using(OleDbConnection connection = new OleDbConnection(.....))
        using(OleDbCommand cmd = new OleDbCommand(cmdText, connection))
        {            
            connection.Open();
            cmd.ExecuteNonQuery();
            button26.Text = "Done Insert"; 
            button26.ForeColor = Color.Lime;
            mainDataGridView.Visible = true;
        }
    }
    catch (Exception ex)
    {
        richTextBox1.Text=("Error "+ex);
        button26.ForeColor = Color.Black;
    }
}

Finally I don't know if your fields are of text type. You pass literal texts so they should be of text type and remember to use parameters when you switch this simple code to your actual values.

Upvotes: 2

Ayaz
Ayaz

Reputation: 2131

Assign Connection property as below line.

OleDbCommand cmd = new OleDbCommand();
cmd.Connection = connection;

Upvotes: 1

blins
blins

Reputation: 2535

Per @Steve's comment, there is no connection associated with the command when you just instantiate it like that. You need to either set the Connection property of the command or better yet use connection.CreateCommand() to create the command in the first place in which case it will already be associated with the connection (cleaner).

Upvotes: 0

Related Questions