SQL 使用 BETWEEN 运算符的查询导致 "Syntax error in number in query expression"

SQL query with BETWEEN operator causes "Syntax error in number in query expression"

我正在使用 MS Access 数据库。我想获取 2 个日期之间的第一个和最后一个记录。但是在使用 BETWEEN 运算符时出现错误:

Syntax error in number in query expression 'Datum_k BETWEEN 3.4.2017. AND 3.4.2017.'.

我的代码:

private void GetPrviZadnjiBrojRacuna()
{
    OleDbCommand commandOD = new OleDbCommand("SELECT Dokument FROM DnevniPromet WHERE (Datum_k BETWEEN " + datumOd + " AND " + datumDo + ") ORDER BY [Datum_k] ASC", dataModel.CS);
    OleDbCommand commandDO = new OleDbCommand("SELECT Dokument FROM DnevniPromet WHERE [Datum_k] >= " + datumOd + " AND [Datum_k] <= " + datumDo + " ORDER BY [Datum_k] DESC", dataModel.CS);

    try
    {
        dataModel.DT.Clear();
        OleDbDataAdapter ODbDA = new OleDbDataAdapter(commandOD);

        if (!dataModel.CS.State.Equals(ConnectionState.Open))
        {
            dataModel.CS.Open();
        }

        // GET OD 
        ODbDA.Fill(dataModel.DT);
        odRacuna = dataModel.DT.Rows[0].ToString();

        // GET DO
        ODbDA.SelectCommand = commandDO; 
        dataModel.DT.Clear();
        ODbDA.Fill(dataModel.DT);

        doRacuna = dataModel.DT.Rows[0].ToString();

        dataModel.CS.Close();
        dataModel.DataLoaded = true;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

正在解决您的代码段的两个问题:

  • 切勿使用字符串插值来构建查询。这有助于 SQL 注入。很多很多话题都围绕着这个。我建议你阅读。
  • 您错过了日期字符串周围的 ' 单引号。

使用参数化查询,一石二鸟:

OleDbCommand commandOD = new OleDbCommand(@"
    SELECT Dokument
    FROM DnevniPromet
    WHERE (Datum_k BETWEEN @datumOd AND @datumDo)
    ORDER BY [Datum_k] ASC", dataModel.CS);

commandOD.Parameters.AddRange(new OleDbParameter[]
{
    new OleDbParameter("@datumOd", datumOd),
    new OleDbParameter("@datumDo", datumDo)
});