2010-02-02 126 views
4

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

- (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]; 
    [email protected]"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新手,我从教程中了解到读取数据库并显示其内容。我如何继续进行插入和再次显示的任务?

+1

使用包装来处理SQLite而不是直接使用C API。它使生活*所以*更容易.... http://cocoaheads.byu.edu/resources/sqlite –

+0

这里是很好的教程可用。 点击[这里](http://dblog.com.au/iphone-development-tutorials/iphone-sdk-tutorial-reading-data-from-a-sqlite-database/)获取链接。 –

回答

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]; 

另一种选择是使用核心数据(可作为SDK 3.0)。核心数据本来就是相当快速和优化的,尽管它限制了你做非标准的东西。尽管它会导致更慢的SQL查询,除非您充分考虑如何使用它。

有一个在iPhone开发中心here

1

的教程要插入具有一定值的用户,你需要创建像SQL INSERT语句。比方说,用户对象有一个姓氏和名字,那么它看起来像:

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

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); 
    } 
相关问题