C#插入访问抛出异常

C# Insert Into Access Throwing Exception

我有插入 Access 数据库的代码。

此代码通常有效,但我有一个 table 无效,我不明白为什么。

这是我得到的异常:

Syntax error in INSERT INTO statement.

这是代码:

if (connection == null) Connect();
command = new OleDbCommand(SQL);
command.Connection = connection;

try
{
    connection.Open();
    command.ExecuteNonQuery();
}
catch (Exception ex) { }
finally { connection.Close(); }

这是 SQL 字符串:

Insert INTO TrackingsDateTimes (trackingDateTimeID, trackingID, dateTime, info) VALUES(1, 0, #02/05/2017 21:37:00#, '')

这是 table TrackingsDateTimes:

trackingDateTimeID Number
trackingID Number
dateTime Date/Time
info Text

我错过了什么?

谢谢,

您正在尝试插入由 # 而不是单引号引起来的日期。

替换成这个

Insert INTO TrackingsDateTimes (trackingDateTimeID, trackingID, dateTime, info) VALUES(1, 0, '#02/05/2017 21:37:00#', '')

编辑:我错了,史蒂夫是对的。

将列命名为保留关键字并不是一个好主意。

DATETIME is reserved

如果您真的想使用该名称(我建议更改它),那么您需要将该名称括在方括号中

Insert INTO TrackingsDateTimes (trackingDateTimeID, trackingID, [dateTime], info) VALUES (.....)

首先,您应该使用参数化查询而不是内联插入变量。另一件事是 dateTime 是 MS Access 中的保留字, 可能 需要使用 backticks [ReservedWord] 进行转义.

这应该能让您在重写查询时有个好的开始

// string qry = "Insert INTO TrackingsDateTimes ( trackingDateTimeID, trackingID, `dateTime`, info) VALUES(@trackingDateTimeID, #trackingID, @dateTime, @info)"
string qry = "Insert INTO TrackingsDateTimes ( trackingDateTimeID, trackingID, [dateTime], info) VALUES(@trackingDateTimeID, #trackingID, @dateTime, @info)"

if (connection == null) Connect();
command = new OleDbCommand(SQL);
command.Connection = connection;
command.Parameters.AddWithValue("@trackingDateTimeID", (int)1);
command.Parameters.AddWithValue("@trackingID", (int)0);
command.Parameters.AddWithValue("@dateTime", DateTime.Parse("2/05/2017 21:37:00");
command.Parameters.AddWithValue("@info", string.Empty);