简体   繁体   English

从 C# 连接到 ms 访问时出现语法错误

[英]syntax error while connecting from c# to ms access

I am able to read from a MS Access database so I know I have set up my connection string correctly, but I keep getting "syntax error" when I try to insert into that MS Access database.我能够从 MS Access 数据库中读取数据,因此我知道我已经正确设置了连接字符串,但是当我尝试插入该 MS Access 数据库时,我不断收到“语法错误”。 I tried running the same query in Access directly and it works with no errors.我尝试直接在 Access 中运行相同的查询,并且没有错误。 Your help will be much appreciated.您的帮助将不胜感激。

public void connect()
{
    conn = new OleDbConnection(conn_string);
    conn.Open();
}

public void closeConnection()
{
    conn.Close();
}  

{
    connect();

    // submitQuery = "INSERT INTO TaskSchedular(Grade, Month, Day, Subject, DueDate, AssignmentLink, OrigScore, FinalScore, Task, Priority)  VALUES('8', '17', '10', 'test', '12', 'test', '12', '34', 'test', '2');";

    OleDbCommand cmdInsert = new OleDbCommand();
    cmdInsert.Connection = conn;
    cmdInsert.CommandText = "INSERT INTO TaskSchedular(Grade, Month, Day, Subject, DueDate, AssignmentLink, OrigScore, FinalScore, Task, Priority)  VALUES('8', '17', '10', 'test', '12', 'test', '12', '34', 'test', '2');";

    cmdInsert.ExecuteNonQuery();
                
    closeConnection();
}
catch (Exception ex)
{
    error_msg = ex.Message;
    //MessageBox.Show(error_msg);
}

Day and Month are reserved words in Access, so they need to be enclosed in square brackets. DayMonth是 Access 中的保留字,因此需要将它们括在方括号中。 So this part所以这部分

INSERT INTO TaskSchedular(Grade, Month, Day, Subject

should be:应该:

INSERT INTO TaskSchedular(Grade, [Month], [Day], Subject

(There are potentially other issues here, such as specifying numeric values in quotes which probably shouldn't be in quotes, and ideally using parameters instead of putting the values directly in the SQL, but that's slightly separate from this direct question.) (这里可能还有其他问题,例如在引号中指定可能不应该在引号中的数值,并且理想情况下使用参数而不是将值直接放在 SQL 中,但这与这个直接问题略有不同。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM