如何使用C#删除SQLite中lastVisited早于指定天数的行?
C#删除SQLite中
lastVisited早于指定天数的记录 先明确时间存储格式
SQLite的REAL类型存储时间通常有两种常见场景,得先对应你的数据格式:
- Unix时间戳(秒):从1970-01-01 UTC到记录时间的总秒数,以double类型存储
- OLE自动化日期:.NET中
DateTime.ToOADate()生成的double值,以1899-12-30为基准的天数
代码实现(使用Microsoft.Data.Sqlite驱动)
先通过NuGet安装Microsoft.Data.Sqlite包,这是微软维护的官方驱动,兼容性更好。
情况1:lastVisited为Unix时间戳
using Microsoft.Data.Sqlite; public void CleanExpiredRecords(int daysToKeep) { // 计算daysToKeep天前的UTC时间对应的Unix时间戳 DateTime cutoffTime = DateTime.UtcNow.AddDays(-daysToKeep); double cutoffTimestamp = (cutoffTime - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds; // 替换为你的数据库路径和表名 string connectionString = "Data Source=your_database.db;"; using (var connection = new SqliteConnection(connectionString)) { connection.Open(); string deleteSql = "DELETE FROM YourTableName WHERE lastVisited < @CutoffTimestamp;"; using (var command = new SqliteCommand(deleteSql, connection)) { command.Parameters.AddWithValue("@CutoffTimestamp", cutoffTimestamp); int deletedRows = command.ExecuteNonQuery(); Console.WriteLine($"已删除{deletedRows}条过期记录"); } } }
情况2:lastVisited为OLE自动化日期
using Microsoft.Data.Sqlite; public void CleanExpiredRecords(int daysToKeep) { // 计算daysToKeep天前的OLE日期值(注意时区:用UtcNow还是Now取决于你存储的是UTC还是本地时间) DateTime cutoffTime = DateTime.UtcNow.AddDays(-daysToKeep); double cutoffOADate = cutoffTime.ToOADate(); string connectionString = "Data Source=your_database.db;"; using (var connection = new SqliteConnection(connectionString)) { connection.Open(); string deleteSql = "DELETE FROM YourTableName WHERE lastVisited < @CutoffOADate;"; using (var command = new SqliteCommand(deleteSql, connection)) { command.Parameters.AddWithValue("@CutoffOADate", cutoffOADate); int deletedRows = command.ExecuteNonQuery(); Console.WriteLine($"已删除{deletedRows}条过期记录"); } } }
核心注意事项
- 务必替换代码中的
your_database.db和YourTableName为实际的数据库路径与表名 - 时区要匹配:如果
lastVisited存储的是UTC时间,计算截止时间时要用DateTime.UtcNow;如果是本地时间则用DateTime.Now,避免因时区偏差删错记录 - 始终使用参数化查询:既能防止SQL注入,又能保证数据类型匹配,避免转换错误
- 删除前建议先验证:执行
SELECT * FROM YourTableName WHERE lastVisited < @Cutoff;确认要删除的记录符合预期,再执行DELETE操作
内容的提问来源于stack exchange,提问作者HelloCW
相关产品推荐
相关产品推荐

