我在操作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();
}
为什么我不能将记录写入该数据库的表中?如何查看记录的单元格?
答案 0 :(得分:1)
Name
是Access SQL中的reserved word,因此您需要将该列名称包装在方括号([]
)中。试试这个:
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