简体   繁体   English

SQLite 数据库与 C# 无法比较日期时间数据类型

[英]SQLite database with C# Unable to compare datetime datatype

I am using C# (.NET) and SQLite database with it.我正在使用 C# (.NET) 和 SQLite 数据库。 I have a table in an SQLite database with a column called "InvoiceDate".我在 SQLite 数据库中有一个表,其中有一列名为“InvoiceDate”。 I have chosen the datatype (in the db table) for the same as TEXT as I need it to be a datetime variable.我选择了与 TEXT 相同的数据类型(在 db 表中),因为我需要它作为日期时间变量。

I am using the System.Data.SQLite reference .我正在使用System.Data.SQLite reference

The following is my command text where I am facing the problem:以下是我遇到问题的命令文本:

command.CommandText = "SELECT * FROM InvoiceMaster WHERE InvoiceDate BETWEEN '" 
                     + date1.ToString() + "' AND '" 
                     + date2.ToString() + "' ORDER BY InvoiceNumber";

I need to find all results where the column InvoiceDate falls between the given dates date1 and date2.我需要找到 InvoiceDate 列落在给定日期 date1 和 date2 之间的所有结果。 But the problem is that I am getting the results even though I choose other dates for example I get the same results for the same month and dates even though I choose a different year.但问题是,即使我选择了其他日期,我也得到了结果,例如,即使我选择了不同的年份,我也得到了相同月份和日期的相同结果。 There is something wrong with the command text and I also need to know what type of datatype should I choose in the db table.命令文本有问题,我还需要知道应该在 db 表中选择什么类型的数据类型。 Please do let me know how I should be writing the select command.请让我知道我应该如何编写选择命令。

From 1.2 Date and Time Datatype1.2 日期和时间数据类型

TEXT as ISO8601 strings ("YYYY-MM-DD HH:MM:SS.SSS") TEXT作为 ISO8601 字符串(“YYYY-MM-DD HH:MM:SS.SSS”)

Since ToString() does not generate this kind of format, you can use custom formatting like;由于ToString()不会生成这种格式,因此您可以使用自定义格式,例如;

date1.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture)
date2.ToString("yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture)

But more important, you should always use parameterized queries .但更重要的是,您应该始终使用参数化查询 This kind of string concatenations are open for SQL Injection attacks.这种字符串连接对SQL 注入攻击是开放的。

I'm not %100 about format but you might wanna use The "o" standard format specifier which represents;我不是 %100 关于格式,但您可能想使用代表"o"标准格式说明符

.. a custom date and time format string using a pattern that preserves time zone information and emits a result string that complies with ISO 8601. .. 使用保留时区信息并发出符合 ISO 8601 的结果字符串的模式的自定义日期和时间格式字符串。

command.CommandText = @"SELECT * FROM InvoiceMaster 
                        WHERE InvoiceDate BETWEEN @date1 AND @date2 
                        ORDER BY InvoiceNumber";

command.Parameters.AddWithValue("@date1", date1.ToString("o"));
command.Parameters.AddWithValue("@date2", date1.ToString("o));

You can create a method to convert your datetime您可以创建一种方法来转换您的日期时间

 private string DateTimeSQLite(DateTime datetime)
  {
    string dateTimeFormat = "{0}-{1}-{2} {3}:{4}:{5}.{6}";
    return string.Format(dateTimeFormat, datetime.Year,   
                         datetime.Month,datetime.Day, 
                         datetime.Hour, datetime.Minute,  
                          datetime.Second,datetime.Millisecond);
  }

or better make it a extension method.或者更好地使它成为一种扩展方法。

 private static string DateTimeSQLite(this DateTime datetime)
 {}

Also use parametrized queries to avoid sql injection还可以使用参数化查询来避免 sql 注入

string commandText = "SELECT * FROM InvoiceMaster 
                  WHERE InvoiceDate BETWEEN @date1 and @date2
                  ORDER BY InvoiceNumber"
yourcommand.Parameters.Add("@date1",date1.DateTimeSQLite());
yourcommand.Parameters.Add("@date2",date1.DateTimeSQLite());

Since you have chosen to store the dates as TEXT field in the database, they must be formatted using ISO8601.由于您已选择将日期作为TEXT字段存储在数据库中,因此必须使用 ISO8601 对其进行格式化。 Example:例子:

2016-02-03T20:34:22Z

So once you have ensured that they are stored this way all that's left is parametrize your query:因此,一旦您确保它们以这种方式存储,剩下的就是参数化您的查询:

DateTime date1 = ... get from somewhere
DateTime date2 = ... get from somewhere

using (var conn = new SQLiteConnection("Data Source=mydb.db;Version=3;"))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "SELECT * FROM InvoiceMaster WHERE InvoiceDate BETWEEN @startDate AND @endDate";
    cmd.Parameters.AddWithValue("@startDate", date1.ToString("o"));
    cmd.Parameters.AddWithValue("@endDate", date2.ToString("o"));
    using (var reader = cmd.ExecuteReader())
    {
        while (reader.Read())
        {
            // do something with the results here
        }
    }
}

Notice how I am using the .ToString("o") format specifier to ensure that the dates will be passed correctly to the database.请注意我如何使用.ToString("o")格式说明符来确保将日期正确传递到数据库。

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

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