【发布时间】:2013-08-19 16:23:13
【问题描述】:
我在一个 sqlite 数据库中有一个表,它有一个日期变量。我在这段代码中设置了一个函数,告诉我那天的日期是什么:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
self.dateFormatter = [[NSDateFormatter alloc] init];
[self.dateFormatter setDateStyle:NSDateFormatterShortStyle];
[self.dateFormatter setTimeStyle:NSDateFormatterNoStyle];
_todayDate = [self.dateFormatter stringFromDate:[NSDate date]];
然后我创建一个使用日期的 sql 语句:
-(void) readRecordsFromDatabaseWithPath:(NSString *)filePath {
sqlite3 *database;
if (sqlite3_open([filePath UTF8String], &database) == SQLITE_OK) {
const char *sqlStateMent = "select * from records where date = ?";
sqlite3_stmt *compiledStatement;
NSLog(@"%d", sqlite3_prepare(database, sqlStateMent, -1, &compiledStatement, NULL));
if (sqlite3_prepare_v2(database, sqlStateMent, -1, &compiledStatement, NULL) == SQLITE_OK) {
sqlite3_bind_text(compiledStatement, 1, [_todayDate UTF8String], -1, SQLITE_TRANSIENT);
while (sqlite3_step(compiledStatement) == SQLITE_ROW) {
NSString *recordid = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 0)];
NSString *patientid = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
NSString *treatmentid = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 2)];
NSString *date = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 3)];
NSString *name = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 4)];
NSString *area = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 5)];
NSString *level = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 6)];
NSString *shots = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 7)];
Record *newRecord = [[Record alloc] init];
newRecord.patientid = patientid;
newRecord.recordid = recordid;
newRecord.treatmentid = treatmentid;
newRecord.date = date;
newRecord.name = name;
newRecord.area = area;
newRecord.level = level;
newRecord.shots = shots;
LSAppDelegate *delegate = (LSAppDelegate *)[[UIApplication sharedApplication] delegate];
[delegate.records addObject:newRecord];
}
}
sqlite3_finalize(compiledStatement);
}
sqlite3_close(database);
}
然后最后调用函数:
NSString *filePath = [self copyDatabaseToDocuments];
[self readRecordsFromDatabaseWithPath:filePath];
[self.tableView reloadData];
虽然我对 Objective-c 很陌生,而且通常人们希望看到一些代码,但对于大量代码感到抱歉。
【问题讨论】:
-
你的问题是什么?无论如何,可能的答案是日期值的格式不匹配。
-
你想要所有日期为“今天”的记录吗?如果是,请参阅我的答案。
-
@ollie-cole 此评论与您的问题无关。我建议您使用FMDB Framework 进行所有数据库操作。你可以参考这个answer
标签: ios sql objective-c sqlite nsdateformatter