创建数据库
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *ducumentsDirectory = [paths objectAtIndex:0];
NSString *dataBaseFile = [ducumentsDirectory stringByAppendingPathComponent:kDatabaseName];
sqlite3 *database;
//打开数据库如果数据不存在则创建数据库
if (sqlite3_open([dataBaseFile UTF8String], &database) != SQLITE_OK) {
NSLog(@"==Open sqlite3 fail==");
sqlite3_close(database);
}
NSString *createSQL = @"CREATE TABLE IF NOT EXISTS FIELDS (TAG INTEGER PRIMARY KEY, FIELD_DATA TEXT);";
char *errorMsg;
//创建一个表格
if (sqlite3_exec(database, [createSQL UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK) {
sqlite3_close(database);
NSAssert(0, @"创建数据库表错误: %s", errorMsg);
}
sqlite3_close(database);
创建数据库=结束///
///向数据库写入数据
if (sqlite3_open([dataBaseFile UTF8String], &database)
!= SQLITE_OK) {
sqlite3_close(database);
NSAssert(0, @"打开数据库失败!");
}
//向表格插入四行数据
for (int i = 1; i <= 4; i++) {
//这个时相数据库里面写入的数据
NSString *writeData = [NSString stringWithFormat:@"Data{%d}",i];
//使用约束变量插入数据
char *update = "INSERT OR REPLACE INTO FIELDS (TAG, FIELD_DATA) VALUES (?, ?);";
sqlite3_stmt *stmt;
if (sqlite3_prepare_v2(database, update, -1, &stmt, nil) == SQLITE_OK) {
sqlite3_bind_int(stmt, 1, i);
sqlite3_bind_text(stmt, 2, [writeData UTF8String], -1, NULL);
}
char *errorMsg = NULL;
if (sqlite3_step(stmt) != SQLITE_DONE)
NSAssert(0, @"更新数据库表FIELDS出错: %s", errorMsg);
sqlite3_finalize(stmt);
}
数据库写入数据=结束
读取数据库
sqlite3_stmt *stmt2;
NSString *query = @"SELECT TAG, FIELD_DATA FROM FIELDS ORDER BY TAG";
if (sqlite3_prepare_v2(database, [query UTF8String], -1, &stmt2, nil) == SQLITE_OK) {
//依次读取数据库表格FIELDS中每行的内容,并显示在对应的TextField
while (sqlite3_step(stmt2) == SQLITE_ROW) {
//获得数据
int tag = sqlite3_column_int(stmt2, 0);
char *rowData = (char *)sqlite3_column_text(stmt2, 1);
//从数据库中获取到的数据
NSLog(@"===tag={%d}==rowData=={%s}==",tag,rowData);
}
sqlite3_finalize(stmt2);
}
//关闭数据库
sqlite3_close(database);
读数据库结束/