详解iPhone连接Sqlite数据库 实例操作是本文要介绍的内容,主要是以代码实现,来讲述了一些iPhone连接Sqlite数据库的代码,来看详细内容。
相信在N多应用中要涉及数据库操作
- 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);结束退出
小结:详解iPhone连接Sqlite数据库 实例操作的内容介绍完了,希望本文对你有所帮助!