0

I'm having difficulty manipulating an Access 2007 database. My code is this:

using (OleDbConnection connection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\User\\db.accdb;Jet OLEDB:Database Password=" + password + ";Persist Security Info=False"))
{
    connection.Open();
    string query = "INSERT INTO Book(Name, Author) VALUES('Hello', 'World')"; ;
    OleDbCommand cmd = new OleDbCommand(query, connection);
    cmd.ExecuteNonQuery();
    connection.Close();
}

Why can't I write the record to the table of that database? How can I view the cell of the record?

1
  • What happens when you run it? Commented Oct 16, 2013 at 15:23

1 Answer 1

1

Name is a reserved word in Access SQL, so you need to wrap that column name in square brackets ([]). Try this instead:

string query = "INSERT INTO Book ([Name], Author) VALUES ('Hello', 'World')";

Edit re: comments

With the information presented so far I can see no reason why your INSERT query should fail with "Operation must use an updateable query". For what it's worth, the following C# code successfully adds a row to the [Book] table...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.OleDb;

namespace oleDbTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string myConnectionString;
            myConnectionString =
                    @"Provider=Microsoft.ACE.OLEDB.12.0;" +
                    @"Data Source=C:\Users\Public\Database1.accdb;";

            using (var con = new OleDbConnection())
            {
                con.ConnectionString = myConnectionString;
                con.Open();

                using (var cmd = new OleDbCommand())
                {
                    cmd.Connection = con;
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText =
                        @"INSERT INTO Book (Denomination, Author) VALUES ('Hello', 'World')";
                    cmd.ExecuteNonQuery();
                }
                con.Close();
            }
            Console.WriteLine("Done.");
        }
    }
}

...like so:

Denomination  Author
------------  ------
Hello         World 
Sign up to request clarification or add additional context in comments.

3 Comments

I've changed "Name" with "Denomination" but not function because the error is below "Operation must use an updateable query"
@MikeSmith Can you open the database in Access itself and verify that you can add a new row to [Book] by typing values into a Datasheet View?
In Access you can insert a new row, but in C# code from the above error

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.