iOS SQLite数据库存储时间Two(不使用第三方数据库管理,苹果原生api)

里面有一个关于SQLite3 存 时间的文章了,不过我看了觉得还是有很多让新手模糊的地方,在这里简单的介绍下。我这里没有使用任何第三方。苹果原生。

1.首先,获取或者说得到一个时间,string或者date 格式。

NSDate *date = [NSDate date];

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

[formatter setDateStyle:NSDateFormatterMediumStyle];

[formatter setTimeStyle:NSDateFormatterShortStyle];

[formatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];

NSString *DateTime = [formatter stringFromDate:date];

2.string转换成date格式

NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];

[dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSDate *date =[dateFormat dateFromString:strtime];

3.创建数据库&表&字段

static sqlite3 *db = nil;

+(BOOL)openDatabase{

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *path = [documentsDirectory stringByAppendingPathComponent:@"数据库名"];

if(sqlite3_open([path UTF8String], &db) != SQLITE_OK) {

sqlite3_close(db);

return NO;

}else{

return YES;

}

}

这个有BUG ,我代码下边的复制不出来了。。。好尴尬。。。


4.创建完成之后,写入数据。

sqlite3_stmt *statement = nil;

BOOL isSuccess          = NO ;

const char* sql = "insert INTO 表名 (字段名称) VALUES(?)";

if(sqlite3_prepare_v2(db, sql, -1, &statement, nil) == SQLITE_OK){

NSAssert1(1, @"Error while creating update statement. '%s'", sqlite3_errmsg(db));

sqlite3_bind_double(statement, 1, [date格式的时间   timeIntervalSince1970]);

if(SQLITE_DONE != sqlite3_step(statement))

{

isSuccess = NO;

NSAssert1(1, @"Error while insertAreaInfo. '%s'", sqlite3_errmsg(db));

}else{

isSuccess = YES;

}

sqlite3_finalize(statement);

这样就写入完成了

你可能感兴趣的:(iOS SQLite数据库存储时间Two(不使用第三方数据库管理,苹果原生api))