查询中的语法错误

时间:2012-02-16 22:05:53

标签: c#

我是编程新手,正在Access中开发新的桌面数据库应用程序,我正在尝试将数据插入表中。我有两个日期时间选择器,我从中读取它的值

jobcodedatabean.PaperRecievedate1 = dtpjobcodedate.Value.Date;
jobcodedatabean.Shipmenentdate = dtpshipmentdate.Value.Date;

我已将数据库传递给函数

 public void addaction(JobCodeDataBean jobcodedatabean)
    {
        MessageBox.Show(jobcodedatabean.Shipmenentdate.ToString());

        try
        {

            OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(connString);
            oleDbConnection1.Open();
            OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("INSERT INTO jobcodemastertable (jobcode ,customercode,totaltrip,shipmentdate,fromPlace, destination,description ,packagetype ,noofpackage ,contactperson ,jobecodedate ) Values ('" + jobcodedatabean.Jobcode + "', '" + jobcodedatabean.Customercode + "' ," + jobcodedatabean.Totaltrip + "," + jobcodedatabean.Shipmenentdate + " ,'" + jobcodedatabean.Fromplace + "','" + jobcodedatabean.Destination + "','" + jobcodedatabean.Description + "','" + jobcodedatabean.Typeofpackage + "','" + jobcodedatabean.Noofpackages + "','" + jobcodedatabean.Contactperson + "'," + jobcodedatabean.PaperRecievedate1 + ") ", oleDbConnection1);
            oleDbCommand1.CommandType = CommandType.Text;
            oleDbCommand1.ExecuteNonQuery();

            oleDbConnection1.Close();

       }
       catch (Exception)
        {
            MessageBox.Show(e);

        }

但是我在查询中得到了例外

Syntax error (missing operator) in query expression '2/16/2012 12:00:00 AM'. 

在访问中,日期字段采用短日期格式

请帮助解决我的错误

2 个答案:

答案 0 :(得分:3)

报价不正确。要避免这些错误,请使用有序参数:

var myCommand = new OleDbCommand(
    "INSERT INTO MyTable(someDateField, someTextField, someNumberField) VALUES (?, ?, ?)"
);

myCommand.Parameters.Add(DateTime.Now);
myCommand.Parameters.Add("Some text");
myCommand.Parameters.Add(123);

使用参数还有助于防范SQL injection attacks。在您的示例中,如果其中一个字符串包含撇号,则除非您正确地将其转换为两个撇号,否则它将失败。使用参数可以自动正确转义。

答案 1 :(得分:2)

您忘了在引号中附上日期:

... ",'" + jobcodedatabean.Shipmenentdate + "' ,'" ...
... "','" + jobcodedatabean.PaperRecievedate1 + "') " ...

注意两个日期的单引号。