我通过FMDB执行的任何查询,包括NSDates执行,但不返回结果集或对数据库进行编辑。我在ios 4.3模拟器工作。其他没有规定日期的查询可以正确执行。下面是我使用的代码摘录:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd hh-mm-ss"];
NSDate *start = [dateFormatter dateFromString:@"2011-07-18 06:40:21" ];
NSDate *end = [dateFormatter dateFromString:@"2011-07-18 06:41:19"];
[dateFormatter release];
FMDatabase* db = [FMDatabase databaseWithPath:appDelegate.databasePath];
if (![db open]) {
NSLog(@"Could not open db.");
}
[db beginTransaction];
[db executeUpdate:@"delete from time_stamp_table where time_stamp >= ?
and time_stamp <= ?",start,end];
NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
[db commit];
[db close];
模式在time_stamped_table中声明time_stamp:
create table time_stamp_table{
id INTEGER PRIMARY KEY,
time_stamp DATETIME NOT NULL
}
当我在命令行中使用存储在模拟应用程序上下文中的数据库在sqlite3中执行这些查询时,它们可以工作。是否有一些特殊的准备查询NSDate与FMDB,我错过了?
查询like
SELECT * from Time_Stamp where updatedTime >= DATE('2011-05-17 06:40:21') AND updatedTime <= DATE('2011-07-19 06:40:21')
在比较日期时获取正确的记录。你可以从这里得到一些提示,并改变你的查询,如
[db executeUpdate:@"delete from time_stamp_table where time_stamp >= DATE(?)
and time_stamp <= DATE(?)",start,end];
或
[db executeQuery:[NSString stringwithFormat:@"delete from time_stamp_table where time_stamp >= DATE('%@')
and time_stamp <= DATE('%@')",start,end];
我没有测试的查询,所以你将不得不测试它自己。希望能有所帮助
尽量避免将NSDate解析为SQL-Query。不如试着用sqlite可以理解的格式解析NSString: '2011-07-18 06:41:19'。如果您希望sqlite比较值,则必须使用特定的日期函数。Sqlite3提供DATE, TIME或DATETIME函数来转换字符串。
其次,为了纠正Rahul Sharma,使用DATE函数比较TIMESTAMP将失败,因为TIMESTAMP同时保存日期和时间。因此应该使用DATETIME函数。
[db executeUpdate:@"delete from time_stamp_table where time_stamp >= DATETIME(?)
and time_stamp <= DATETIME(?);",
@"2011-07-18 06:40:21",
@"2011-07-18 06:41:19"];
可能您已经使用了executeQuery
方法。Delete操作属于更新操作。起初,我使用了executeQuery
,但即使一次又一次检查属性类型也找不到问题。最后executeUpdate
修复了它