0

我在操作 Access 2007 数据库时遇到了困难。我的代码是这样的:

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();
}

为什么我不能将记录写入该数据库的表中?如何查看记录的单元格?

4

1 回答 1

1

Name是 Access SQL 中的保留字,因此您需要将该列名括在方括号 ( []) 中。试试这个:

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

编辑回复:评论

根据目前提供的信息,我看不出您的 INSERT 查询为什么会因“操作必须使用可更新查询”而失败。值得一提的是,以下 C# 代码成功地在 [Book] 表中添加了一行...

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.");
        }
    }
}

...像这样:

Denomination  Author
------------  ------
Hello         World 
于 2013-10-16T15:44:19.853 回答