c# – 使用OleDbCommandBuilder时访问SQL语法错误
作者:互联网
我将使用C#中的OleDbDataAdapter在Access数据库中插入数据,但我在INSERT INTO命令中出现错误消息语法错误
BackgroundWorker worker = new BackgroundWorker();
OleDbDataAdapter dbAdapter new OleDbDataAdapter();
OleDbConnection dbConnection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\\PMS.mdb");
worker = new BackgroundWorker();
worker.WorkerReportsProgress = true;
worker.DoWork += InsertJob;
worker.ProgressChanged += InsertJobCompleted;
worker.RunWorkerAsync(args);
而InsertJob函数是:
private void InsertJob(object sender, DoWorkEventArgs e)
{
var args = (InsertJobArgs)e.Argument;
try
{
dbAdapter.SelectCommand = new OleDbCommand("SELECT * FROM Sheet", dbConnection);
dbAdapter.Fill(args.DataTable);
var builder = new OleDbCommandBuilder(dbAdapter);
var row = args.DataTable.NewRow();
row["UserName"] = args.Entry.UserName;
row["Password"] = args.Entry.Password;
args.DataTable.Rows.Add(row);
dbAdapter.InsertCommand = builder.GetInsertCommand();
dbAdapter.Update(args.DataTable);
builder.Dispose();
}
catch (Exception ex)
{
args.Exception = ex;
worker.ReportProgress(0, args);
return;
}
worker.ReportProgress(100, args);
}
我在线收到错误:dbAdapter.Update(args.DataTable);
我尝试使用visual studio调试它,发现所有InsertCommand参数值都为null
我尝试在调用dbAdapter.Update(args.DataTable)之前通过此代码手动插入它;
dbAdapter.InsertCommand.Parameters[0].Value = args.Entry.UserName;
dbAdapter.InsertCommand.Parameters[1].Value = args.Entry.Password;
解决方法:
试试这个:
紧接着就行了
var builder = new OleDbCommandBuilder(dbAdapter);
添加两行
builder.QuotePrefix = "[";
builder.QuoteSuffix = "]";
这将告诉OleDbCommandBuilder将表和列名称包装在方括号中,生成一个INSERT命令
INSERT INTO [TableName] ...
而不是默认表格
INSERT INTO TableName ...
如果任何表或列名称包含空格或“有趣”字符,或者它们恰好是Access SQL中的保留字,则必须使用方括号. (在您的情况下,我怀疑您的表有一个名为[Password]的列,而PASSWORD是Access SQL中的保留字.)
标签:c,oledb,ms-access 来源: https://codeday.me/bug/20190713/1454503.html