【问题标题】:How to retrieve data from database using WHERE BETWEEN for variables in Sqlite c#如何在Sqlite c#中使用WHERE BETWEEN从数据库中检索数据
【发布时间】:2021-10-14 14:27:29
【问题描述】:

我在消息表中有一个 Sqlite 行 createDate。我想从方法中createDate 介于startDateendDate 局部变量之间的消息中检索所有记录。

任何建议,如何为string stm 编写查询?或任何其他方式如何做到这一点

DateTime endDate = DateTime.Now;
DateTime startDate = endDate.AddDays(-7);

using (SQLiteConnection con = new SQLiteConnection(cs))
{
    con.Open();

    string stm = "SELECT * FROM messages WHERE createDate BETWEEN @startDate AND @endDate";

    using (SQLiteCommand cmd = new SQLiteCommand(stm, con))
    {
        using (SQLiteDataReader rdr = cmd.ExecuteReader())
        {
            while (rdr.Read())
            {
                for (j = 0; j <= rdr.FieldCount - 1; j++)
                {
                    data = rdr.GetValue(j).ToString();
                    xlWorkSheet.Cells[i + 1, j + 1] = data;
                }
                i++;
            }
        }
    }
    con.Close();
}

【问题讨论】:

  • 声明中没有绑定@startDate@endDate
  • @AKX 是的,我想将数据库中的 createDate 行与局部变量 startDate 和 endDate 进行比较,但不知道如何正确编写查询

标签: c# sql sqlite


【解决方案1】:

你应该可以像这样绑定参数(syntax borrowed from here):

string stm = "SELECT * FROM messages WHERE createDate BETWEEN @startDate AND @endDate";

using (SQLiteCommand cmd = new SQLiteCommand(stm, con))
{
   cmd.Parameters.AddWithValue("@startDate", startDate));
   cmd.Parameters.AddWithValue("@endDate", endDate));
   // ...

【讨论】:

  • 但是数据库中没有 startDate 和 endDate,它有什么用?
  • 语句中的@startDate@endDate 参数占位符将替换为您拥有的那些局部变量的值。
【解决方案2】:

SQLLite 要求日期为 YYYY-MM-DD 格式。由于数据库中的数据和查询中的字符串不是这种格式,它可能会将您的“日期”视为字符串。

SELECT * FROM test WHERE date BETWEEN "2021-02-11" AND "2021-08-11";

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    • 2013-03-17
    • 1970-01-01
    相关资源
    最近更新 更多