使用OleDbCommandBuilder时访问SQL语法错误

时间:2013-10-24 05:47:55

标签: c# ms-access oledb

我将使用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;

1 个答案:

答案 0 :(得分:14)

试试这个:

紧接在

之后
var builder = new OleDbCommandBuilder(dbAdapter);

添加两行

builder.QuotePrefix = "[";
builder.QuoteSuffix = "]";

这将告诉OleDbCommandBuilder将表名和列名包装在方括号中,产生一个INSERT命令,如

INSERT INTO [TableName] ...

而不是默认表单

INSERT INTO TableName ...

如果任何表或列名称包含空格或“有趣”字符,或者它们恰好是Access SQL中的保留字,则需要使用方括号。 (在您的情况下,我怀疑您的表有一个名为[Password]的列,而PASSWORD是Access SQL中的保留字。)