连接 iPhone 的sqlite数据库的一段代码例子(转)

一夜长风 2011-10-26

原帖地址http://www.cocoachina.com/bbs/read.php?tid-24840.html相信在N多应用中要涉及数据库操作,下面这段连接iPhone自带的sqllite数据库的代码由CocoaChina会员“mahui”分享,原帖地址http://www.cocoachina.com/bbs/read.php?tid-24840.htmlsqlite3*database;NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);NSString*documentsDirectory=[pathsobjectAtIndex:0];NSString*strPaths=[documentsDirectorystringByAppendingPathComponent:kFilename];if(sqlite3_open([strPathsUTF8String],&database)!=SQLITE_OK){sqlite3_close(database);NSAssert(0,@"Failedtoopendatabse");}NSString*createSQL=@"CREATETABLEIFNOTEXISTSFIELDS(ROWINTEGERPRIMARYKEY,FIELD_DATATEXT)";if(sqlite3_exec(database,[createSQLUTF8String],NULL,NULL,&errorMsg)!=SQLITE_OK){sqlite3_close(database);NSAssert1(1,@"Errorcreatetable:%s",errorMsg);}NSString*query=@"SELECTROW,FIELD_DATAFROMFIELDSORDERBYROW";sqlite3_stmt*statement;if(sqlite3_prepare_v2(database,[queryUTF8String],-1,&statement,nil)==SQLITE_OK){while(sqlite3_step(statement)==SQLITE_ROW){introw=sqlite3_column_int(statement,0);char*rowData=(char*)sqlite3_column_text(statement,1);NSString*fieldName=[[NSStringalloc]initWithFormat:@"field%d",row];NSString*fieldValue=[[NSStringalloc]initWithUTF8String:rowData];UITextField*field=[selfvalueForKey:fieldName];field.text=fieldValue;[fieldNamerelease];//[fieldNamerelease];[fieldValuerelease];}sqlite3_finalize(statement);}sqllite存在沙盒内,所以打开的时候不需要name和password,但由于字符的格式不用,所以需要通过,[nsString,UTF8String]来转换。sqlite3_prepare_v2(database,[queryUTF8String],-1,&statement,nil),这是执行sql语句的命令。statement记录状态。sqlite3_column_*(statement,0);返回字段值sqlite3_finalize(statement);结束退出

相关推荐