SQLite数据库支持的类型
storage classes | description |
---|---|
NULL | The value is a NULL value |
INTEGER | The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value. |
REAL | The value is a floating point value, stored as an 8-byte IEEE floating point number. |
TEXT | The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE). |
BLOB | The value is a blob of data, stored exactly as it was input. |
从表中可以看出SQLite本身是不支持date类型的,在使用FMDB操作数据库时,如果需要存储NSDate类型数据时,可能我们会考虑按TEXT
l类型存储,在执行插入时先将date转成时间戳或者字符串然后再执行插入操作,事实上不用这么复杂,FMDB已经帮我们做了相应的转换处理。
详见FMDataBase.m
...
else if ([obj isKindOfClass:[NSDate class]]) {
if (self.hasDateFormatter)
sqlite3_bind_text(pStmt, idx, [[self stringFromDate:obj] UTF8String], -1, SQLITE_STATIC);
else
sqlite3_bind_double(pStmt, idx, [obj timeIntervalSince1970]);
}
...
首先我们设计表结构的时候需要把待存储的时间字段指定为TEXT
类型,
比如:
NSString *createtbSql = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS '%@' (\
'%@' INTEGER PRIMARY KEY AUTOINCREMENT, \
'%@' TEXT NOT NULL, \
'%@' TEXT NOT NULL, \
'%@' BLOB, \
'%@' TEXT, \
'%@' TEXT)",
tbname ,
@"ID" ,
@"userid",
@"content",
@"links",
@"create_at",
@"last_modified"];
BOOL res = [self.database executeUpdate: createtbSql];
插入数据时,我们直接传NSDate对象。
success = [self.database executeUpdate:@"INSERT INTO topic_drafts (pin, content, links, create_at, last_modified) VALUES (?, ?, ?, ?, ?)",
model.pin,
model.content,
linksdata,
[NSDate date],
[NSDate date]];
if(!success){
DebugLog(@"INSERT failed, %@", [self.database lastError]);
}
读取时使用库方法dateForColumn:
即可获取存储的NSDate对象
NSDate * create_at = [rs dateForColumn:@"create_at"];
默认情况下会将NSDate对象转成时间戳存储在表中,如下图第二行所示
datetime.jpg
当然我们也可以将存储的数据指定为格式化的时间字符串
+ (void)initialize
{
if (self == [DBPersistentManager class]) {
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
__dbDateFormatter = [[NSDateFormatter alloc] init];
[__dbDateFormatter setLocale:[NSLocale currentLocale]];
[__dbDateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
});
}
}
- (instancetype)init
{
self = [super init];
if (self) {
mdatabase = [FMDatabase databaseWithPath:[self dbPath]];
if(mdatabase){
[mdatabase setDateFormat:__dbDateFormatter];
}
}
return self;
}
这样存储在数据表里的数据显示就如上图第一行所示。
网友评论