我想在C#中的现有MS Access数据库表中添加一个新行。但是,当我调用DataAdapter的Update方法时,出现了“INSERT INTO语句中的语法错误”。我的代码是:当我调用DataAdapter.Update()时,为什么此C#代码会生成语法错误?
try
{
// Open the database
OleDbCommand mySelectCommand = new OleDbCommand(strAccessSelect, myAccessConn);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(mySelectCommand);
OleDbCommandBuilder myCommandBuilder = new OleDbCommandBuilder(myDataAdapter);
myAccessConn.Open();
// Get Analogue table
int rowCount = myDataAdapter.Fill(myDataSet, "Analogue");
Console.WriteLine("Row Count: " + rowCount);
DataTable analogues = myDataSet.Tables["Analogue"];
analogues.PrimaryKey = new DataColumn[] { analogues.Columns["Name"] };
// Create a new row.
System.Data.DataRow newRow;
newRow = analogues.NewRow();
newRow["Name"] = "My new row";
newRow["Area"] = "System";
newRow["Description"] = "My new row, created by me!";
analogues.Rows.Add(newRow);
myDataAdapter.InsertCommand = myCommandBuilder.GetInsertCommand();
myDataAdapter.UpdateCommand = myCommandBuilder.GetUpdateCommand();
Console.WriteLine("Insert Command: " + myDataAdapter.InsertCommand.ToString());
Console.WriteLine("Update Command: " + myDataAdapter.UpdateCommand.ToString());
myDataAdapter.Update(myDataSet, "Analogue");
}
catch (Exception ex)
{
Console.WriteLine("Error: Failed to manipulate the DataBase.\n{0}", ex.ToString());
return;
}
finally
{
myAccessConn.Close();
}
我已删除大多数列从表简洁,但所有的列标题都在报价,他们没有包含任何空格,且都不保留字。我没有删除的是Access关键字,但我注意到“NAME”和“Description”是。我不相信这会导致我的问题,因为我已经能够修改现有行中“说明”列中的文本。
命令生成器生成以下对我来说这似乎不太对劲:
System.Data.OleDb.OleDbCommand
我需要手动建立这个命令?如果是这样,我应该使用插入或更新 - 适配器只有一个更新方法,据我所知可以调用更新或插入?
这里是堆栈跟踪与错误:
System.Data.OleDb.OleDbException (0x80040E14): Syntax error in INSERT INTO statement.
at System.Data.Common.DbDataAdapter.UpdatedRowStatusErrors(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
at System.Data.Common.DbDataAdapter.UpdatedRowStatus(RowUpdatedEventArgs rowUpdatedEvent, BatchCommandInfo[] batchCommands, Int32 commandCount)
at System.Data.Common.DbDataAdapter.Update(DataRow[] dataRows, DataTableMapping tableMapping)
at System.Data.Common.DbDataAdapter.UpdateFromDataTable(DataTable dataTable, DataTableMapping tableMapping)
at System.Data.Common.DbDataAdapter.Update(DataSet dataSet, String srcTable)
at SystemMonitor.MainWindow.mnuGenerateSMACS6Interface_Click(Object sender, EventArgs e) in c:\iogen\code\MainWindow.cs:line 436
可帮助:http://stackoverflow.com/q/19557920/284240 –
最好的Q是我s他的SQL插入语句的形式构建数据集...有错误 – apomene
'Console.WriteLine(myDataAdapter.InsertCommand.CommandText);'现在你打印的只是类的名称而不是属性commandtext – Steve