Access SQL syntax error when using OleDbCommandBuilder

元气小坏坏 提交于 2019-11-26 17:48:37

问题


I am going to INSERT data in Access Database using OleDbDataAdapter in C# but i got an error with message Syntax Error in INSERT INTO Command

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

And InsertJob Function is:

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

I recieve Error on line : dbAdapter.Update(args.DataTable);

I tried to debug it with visual studio and found that All the InsertCommand Parameters Values are null

And I tried to insert it manually by this code before call to dbAdapter.Update(args.DataTable);

dbAdapter.InsertCommand.Parameters[0].Value = args.Entry.UserName;
dbAdapter.InsertCommand.Parameters[1].Value = args.Entry.Password;

回答1:


Try this:

Immediately after the line

var builder = new OleDbCommandBuilder(dbAdapter);

add the two lines

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

That will tell the OleDbCommandBuilder to wrap table and column names in square brackets, producing an INSERT command like

INSERT INTO [TableName] ...

instead of the default form

INSERT INTO TableName ...

The square brackets are required if any table or column names contain spaces or "funny" characters, or if they happen to be reserved words in Access SQL. (In your case, I suspect that your table has a column named [Password], and PASSWORD is a reserved word in Access SQL.)



来源:https://stackoverflow.com/questions/19557920/access-sql-syntax-error-when-using-oledbcommandbuilder

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!