當(dāng)初我學(xué)fmdb操作SQLite3使用的時候遇到了一個問題,怎么存儲時間呢洒琢?于是我找了很久才有了答案。今天就分享一下。
MesaSQLite
可以查看sqlite數(shù)據(jù)庫內(nèi)的具體內(nèi)容夫凸,小伙伴們有興趣的可以下一個
- 我當(dāng)時想到了一個方法,使用
FastCoder
把時間轉(zhuǎn)成二進(jìn)制再存儲阱持,發(fā)現(xiàn)并不行夭拌。 - SQLite3存儲時間是以時間戳
NSTimeInterval
的形式,意思就是要存儲的時間距離1970年的秒數(shù),是double
類型。 - 在我們使用fmdb創(chuàng)建表時類型選擇
datetime
,插入時間之前要把時間轉(zhuǎn)成時間戳NSTimeInterval tInterval=[myDate timeIntervalSince1970];//把時間轉(zhuǎn)成時間戳
- 從數(shù)據(jù)庫取出的時候有2種取法
1.NSTimeInterval tIn=[rs doubleForColumn:@"time"];//獲取時間戳 2.NSDate* data=[rs dateForColumn:@"time"];//獲取時間
- 要取出某段時間的數(shù)據(jù)時鸽扁,只要判斷時間戳就行了
注意SQLite是在MRC下運(yùn)行蒜绽,使用完SQLite3之后要及時關(guān)閉,不然會內(nèi)存泄漏
以下是小Demo
//NULL - 空值
//INTERGER - 有符號整數(shù)類型
//REAL - 浮點(diǎn)數(shù)類型
//TEXT - 字符串(其編碼取決于DB的編碼)
//BLOB - 二進(jìn)制表示
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
NSString* documentsPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
NSString* path=[documentsPath stringByAppendingPathComponent:@"time.sqlite"];
//創(chuàng)建數(shù)據(jù)庫
FMDatabase* db=[FMDatabase databaseWithPath:path];
//創(chuàng)建表
if ([db open]) {
NSString* sql=@"create table if not exists timeSql(id integer PRIMARY KEY AUTOINCREMENT,time datetime)";
BOOL result=[db executeUpdate:sql];
if (result) {
NSLog(@"建表成功");
}else{
NSLog(@"建表失敗");
}
}
//存儲以時間戳的形式
//添加2條時間數(shù)據(jù)
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat: @"yyyy-MM-dd HH:mm:ss"];
NSArray* timeArr=@[@"2014-02-21 16:37:05",@"2016-02-21 16:37:05"];
for (int i=0; i<2; i++) {
[db executeUpdate:@"INSERT INTO timeSql(time) VALUES (?)",[dateFormatter dateFromString:timeArr[i]]];
}
//查詢數(shù)據(jù)
//目標(biāo):查詢出比 2015-01-01 00:00:00 要晚的時間
NSDate* myDate=[dateFormatter dateFromString:@"2015-01-01 00:00:00"];
NSTimeInterval tInterval=[myDate timeIntervalSince1970];//把時間轉(zhuǎn)成時間戳
NSString* sqlR=@"select time from timeSql";
FMResultSet* rs=[db executeQuery:sqlR];
while ([rs next]) {
NSTimeInterval tIn=[rs doubleForColumn:@"time"];//獲取查詢數(shù)據(jù)中的時間戳
if (tIn>tInterval) { //比對時間戳
NSDate* data=[rs dateForColumn:@"time"]; //獲取比 2015-01-01 00:00:00 要晚的時間
NSLog(@"%@",[dateFormatter stringFromDate:data]);
}
}
//關(guān)閉數(shù)據(jù)庫
if ([db open]) {
[db close];
}
}
注:相關(guān)內(nèi)容我會繼續(xù)更新桶现。如果想找一些iOS方面的代碼可以關(guān)注我的簡書躲雅,我會持續(xù)更新,大家一起探討探討
在此謝謝大家閱讀??