在.mdb数据库中执行INSERT时的OleDbException

时间:2013-07-02 13:05:53

标签: c# tsql oledbexception

我有一个数据库,其中有一个名为Schedule的表。它看起来像这样:

Schedule
--------
ScheduleID (number)
BackupID   (number)
Repository (text)
Interval   (text)
Type       (text)

现在我尝试将值插入此表中,如下所示:

List<string> scheduleData = this.scheduler.getSchedule();
string repository = scheduleData[0];
string interval = scheduleData[1];
string type = scheduleData[2];

List<string> selectedBackup = this.backupForm.getSelectedUser();
string backupID = selectedBackup[0];

string connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\\db\\dbBackupUtility.mdb";
OleDbConnection conn = new OleDbConnection(connetionString);
conn.Open();
OleDbCommand sql = new OleDbCommand("INSERT INTO Schedule (BackupID, Repository, Interval, Type) VALUES (@BackupID, @Repository, @Interval, @Type)", conn);
sql.Parameters.AddWithValue("@BackupID", backupID);
sql.Parameters.AddWithValue("@Repository", repository);
sql.Parameters.AddWithValue("@Interval", interval);
sql.Parameters.AddWithValue("@Type", type);

sql.ExecuteNonQuery();

conn.Close();  

但是,每次程序执行此行时,我都会收到OleDbException:

sql.ExecuteNonQuery();

我看不到有关异常的任何其他信息,但我尝试使用VS中的查询分析器手动插入值,这很奇怪。我已经使用读卡器或适配器尝试了上述操作,但每次都会出现相同的错误...

例外文字:

Message: "Syntax error in INSERT statement"
StackTrace =    "at System.Data.OleDb.OleDbCommand.ExecuteCommandTextErrorHandling(OleDbHResult hr)
   at System.Data.OleDb.OleDbCommand.ExecuteCommandTextForSingleResult(tagDBPARAMS dbParams, Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteCommandText(Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteCommand(CommandBehavior behavior, Object& executeResult)
   at System.Data.OleDb.OleDbCommand.ExecuteReaderInternal(CommandBehavior behavior, String method)
   at System.Data.OleDb.OleDbCommand.ExecuteNonQuery()
   at WindowsFormsApplication1.BackupUtility.scheduler_VisibleChanged(Object sender, EventArgs e) in c:\Users\Teichler\Dropbox\VS_Projects\Projects\WindowsFormsApplication1\WindowsFormsApplication1\MainForm.cs:Line104."
Inner Exception: null

3 个答案:

答案 0 :(得分:2)

Intervalkeyword for Jet/Access,将您的命令更改为此(带括号的环绕间隔):

OleDbCommand sql = new OleDbCommand("INSERT INTO Schedule (BackupID, Repository, [Interval], Type) VALUES (@BackupID, @Repository, @Interval, @Type)", conn);

答案 1 :(得分:0)

此错误即将发生,因为您有一个值null,您将其作为要插入的参数传递。该值的表格列不接受NULL

调试你的代码。识别NULL变量并使其成为正确的数据类型。

使用? instaed @。

答案 2 :(得分:0)

它可能是因为Type是sql中的关键字。尝试更改您的声明

"INSERT INTO Schedule (BackupID, Repository, Interval, Type)

"INSERT INTO Schedule (BackupID, Repository, Interval, [Type])

围绕括号中的类型