如何将数据插入iPhone中的SQLite数据库

时间:2010-02-02 14:48:14

标签: iphone objective-c insert sqlite

我是iPhone开发的新手。我想将某些数据插入我的数据库并检索它 并将其显示在表格中。我用表'user'创建了Database data.sqlite。该表有两个值,id(varchar)和name(varchar)。我通过“插入用户值('1','xxxx')在表中插入了3行数据;”在终端窗口。我创建了一个名为“testDb”的基于导航的应用程序。在AppDelegate我有两种方法

- (void)createEditableCopyOfDatabaseIfNeeded {
    NSLog(@"Creating editable copy of database");
    // First, test for existence.
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"data.sqlite"];
    success = [fileManager fileExistsAtPath:writableDBPath];
    if (success) return;
    // The writable database does not exist, so copy the default to the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"data.sqlite"];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
    if (!success) {
        NSAssert1(0, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
}

+(sqlite3 *) getNewDBConnection{
    sqlite3 *newDBconnection;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"data.sqlite"];
    // Open the database. The database was prepared outside the application.
    if (sqlite3_open([path UTF8String], &newDBconnection) == SQLITE_OK) {
        NSLog(@"Database Successfully Opened :)");
    }
    else {
        NSLog(@"Error in opening database :(");
    }
    return newDBconnection;
}

在rootviewcontroller中

-(void)initializeTableData{
    sqlite3 *db=[DatabaseTestAppDelegate getNewDBConnection];
    sqlite3_stmt *statement=nil;
    const char *sql="select * from user";
    if (sqlite3_prepare_v2(db, sql, -1, &statement, NULL)!=SQLITE_OK)
        NSAssert1(0,@"error in preparing staement",sqlite3_errmsg(db));
    else {
        while(sqlite3_step(statement)==SQLITE_ROW)
            [tableData addObject:[NSString stringWithFormat:@"%s",(char*)sqlite3_column_text(statement,1)]];
    }
    sqlite3_finalize(statement);
}

- (void)viewDidLoad {
    [super viewDidLoad];
    tableData=[[NSMutableArray alloc]init];
    [self addMyObjectIntoDatabase];
    [self initializeTableData];
    self.title=@"Database test";
}

显示内容

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    NSLog(@"before displaying data");
    cell.textLabel.text=[tableData objectAtIndex:indexPath.row];
    NSLog(@"after displaying data");
    // Configure the cell.
    return cell;
}

这样可以正常显示表格的内容。但现在我想在我的表中插入另一行并显示插入的内容以及之前的内容。由于我是iPhone的新手,我从教程中学到了读取数据库并显示其内容。如何进一步完成插入和显示的任务?

4 个答案:

答案 0 :(得分:4)

如果您真的对学习如何使用SQLite管理iPhone应用程序中的数据感兴趣,我建议您完成以下教程,因为它是一个非常好的介绍:

iphone-programming-tutorial-creating-a-todo-list-using-sqlite-part-1

本教程使用SQLite处理iPhone应用程序中的数据选择,更新,插入和删除。

答案 1 :(得分:1)

你基本上有两个推荐的选项(并且使用C类不是其中之一)。 许多开发人员都使用FMDB作为Sqlite的包装器。 http://code.google.com/p/flycode/source/browse/trunk/fmdb FMDB重量轻,易于使用。

以下是一个示例电话:

NSString *path = [documentsDirectory stringByAppendingPathComponent:@"mysqlite.db"];    
appSettings.dao = [FMDatabase databaseWithPath:path];
FMResultSet *rs = [[appSettings dao] executeUpdate:@"SELECT * FROM mytable"];
while ([rs next]){
  // do stuff ...
}

这假设我的AppDelegate .m文件中有ApplicationSettings实例。

ApplicationSettings *appSettings = [ApplicationSettings sharedApplicationSettings];

插入也很简单:

sql = [NSString stringWithFormat:@"INSERT INTO table (intCol1, strCol2) VALUES ('%d','%@')", myObj.theNumber, myObj.theString];
[appSettings.dao executeUpdate:sql];

另一种选择是使用Core Data(从SDK 3.0开始提供)。核心数据意味着非常快速和优化,尽管它确实限制你做非标准的东西。虽然它可能导致较慢的SQL查询,除非您充分考虑如何使用它。

iPhone开发中心here

上有一个教程

答案 2 :(得分:1)

要插入具有特定值的用户,您需要创建一个类似的SQL插入语句。假设User对象有一个名字和姓氏,它看起来像:

NSString *insertStatement = [NSString stringWithFormat:@"INSERT INTO USER (FIRSTNAME, LASTNAME) VALUES (\"%@\", \"%@\")", user.firstName, user.lastName];

char *error;
if ( sqlite3_exec(databaseHandle, [insertStatement UTF8String], NULL, NULL, &error) == SQLITE_OK)

您可以在以下位置查看完整示例: http://www.apptite.be/tutorial_ios_sqlite.php

答案 3 :(得分:1)

请检查:

dbName = @"db.sqlite";
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [documentPaths objectAtIndex:0];
dbPath = [documentsDir stringByAppendingPathComponent:dbName];
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:dbPath];
if(success) return;
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:dbName];
[fileManager copyItemAtPath:databasePathFromApp toPath:dbPath error:nil];

 sqlite3 *database ;
[app checkAndCreateDatabase];
// Open the database from the users filessytem
if(sqlite3_open([app.dbPath UTF8String], &database) == SQLITE_OK)
{
    sqlite3_stmt *compiledStatement1;
    NSString* query;

   query=[NSString stringWithFormat:@ " insert into test ( name  ,  company ,  phone ,  email ,  address ,  country ,  state ,  city,  zip , online_id , in_time , flag_delete, flag_update,type_id) values (?, ?, ?,?,?, ?, ?, ?, ?,?,?,? ,?,?)"];



    const char *compiledStatement = [query UTF8String];
    if(sqlite3_prepare_v2(database, compiledStatement, -1, &compiledStatement1, NULL) == SQLITE_OK)
    {
        sqlite3_bind_text(compiledStatement1, 1, [text  UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(compiledStatement1, 2, [text UTF8String], -1, SQLITE_TRANSIENT);
        sqlite3_bind_text(compiledStatement1, 3, [text UTF8String], -1, SQLITE_TRANSIENT);
}
    // Loop through the results and add them to the feeds array
       if(SQLITE_DONE != sqlite3_step(compiledStatement1))
        NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
    sqlite3_finalize(compiledStatement1);
    sqlite3_close(database);
   }