日期:2014-05-16  浏览次数:20463 次

连接 iPhone 的sqlite数据库的一段代码例子(转)
原帖地址 http://www.cocoachina.com/bbs/read.php?tid-24840.html 相信在N多应用中要涉及数据库操作,下面这段连接 iPhone 自带的 sqllite 数据库的代码由 CocoaChina 会员 “mahui” 分享,原帖地址 http://www.cocoachina.com/bbs/read.php?tid-24840.html sqlite3 *database; NSArray *paths= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *strPaths = [documentsDirectory stringByAppendingPathComponent:kFilename]; if (sqlite3_open([strPaths UTF8String], &database) != SQLITE_OK) { sqlite3_close(database); NSAssert(0, @"Failed to open databse"); } NSString *createSQL = @"CREATE TABLE IF NOT EXISTS FIELDS (ROW INTEGER PRIMARY KEY, FIELD_DATA TEXT)"; if(sqlite3_exec(database, [createSQL UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK){ sqlite3_close(database); NSAssert1(1, @"Error create table :%s", errorMsg); } NSString *query = @"SELECT ROW ,FIELD_DATA FROM FIELDS ORDER BY ROW"; sqlite3_stmt *statement; if(sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil) == SQLITE_OK){ while (sqlite3_step(statement) == SQLITE_ROW) { int row = sqlite3_column_int(statement, 0); char *rowData = (char *)sqlite3_column_text(statement, 1); NSString *fieldName = [[NSString alloc] initWithFormat:@"field%d", row]; NSString *fieldValue = [[NSString alloc] initWithUTF8String:rowData]; UITextField *field = [self valueForKey:fieldName]; field.text = fieldValue; [fieldName release]; //[fieldName release]; [fieldValue release]; } sqlite3_finalize (statement); } sqllite存在沙盒内,所以打开的时候不需要name和password,但由于字符的格式不用,所以需要通过,[nsString, UTF8String]来转换。 sqlite3_prepare_v2(database, [query UTF8String], -1, &statement, nil),这是执行sql语句的命令。statement记录状态。 sqlite3_column_*(statement, 0);返回字段值 sqlite3_finalize (statement);结束退出