2011-06-22 119 views
0

通過以下代碼我從Db中檢索數據,但是我需要在select語句之前使用此代碼將一些數據插入到Sqlite3數據庫中。任何人都可以告訴我需要插入查詢的位置以及如何執行它。如何將一些數據插入到Sqlite 3數據庫中

我通過下面的代碼選擇DATAS:

sqlite3* database; 

- (void)initializeDatabase 
{ 
    list=[[NSMutableArray alloc] init]; 
    BOOL success; 
    NSFileManager *filemanager=[NSFileManager defaultManager]; 
    NSError *error; 
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory= [paths objectAtIndex:0]; 
    NSString *writablePath=[documentsDirectory stringByAppendingPathComponent:@"SymbolTalk.sqlite"]; 
    success=[filemanager fileExistsAtPath:writablePath]; 
    if(!success) 
    { 
     NSString *defaultDBPath=[[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"SymbolTalk.sqlite"]; 
     success=[filemanager copyItemAtPath:defaultDBPath toPath:writablePath error:&error]; 
     if(!success) 
     { 
      NSAssert1(0,@"Failed to create writable databasefile withw message %@.",[error localizedDescription]); 
     } 
    } 

    //Specify where to get the database from 
    NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory= [paths objectAtIndex:0]; 
    NSString *path=[documentsDirectory stringByAppendingPathComponent:@"SymbolTalk.sqlite"]; 

    //Open the database 
    //might have to make database as property 
    if(sqlite3_open([path UTF8String], &dataBase) ==SQLITE_OK) 
    { 
     const char *sql="select filename from scenes"; 
     sqlite3_stmt *statement; 

     if(sqlite3_prepare(dataBase, sql, -1, &statement, NULL) == SQLITE_OK) 
     { 
      while (sqlite3_step(statement) == SQLITE_ROW) 
      { 
       //NSLog(@"%@",[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]); 
       [list addObject:[NSString stringWithUTF8String:(char *)sqlite3_column_text(statement, 0)]]; 
      } 
     } 
    } 
} 
+0

什麼是你所得到的錯誤? –

+0

此代碼用於檢索數據。我需要代碼來插入 – Christina

回答

1
sqlite3_stmt *insert_statement = nil; 

const char *sql = "INSERT INTO scenes (filename) VALUES(?)"; 
if (sqlite3_prepare_v2(database, sql, -1, &insert_statement, NULL) != SQLITE_OK) { 
    NSAssert1(NO, @"Error: failed to prepare statement with message '%s'.", sqlite3_errmsg(database)); 
} 

sqlite3_bind_text(insert_statement, 1, [newFilename UTF8String], -1, SQLITE_TRANSIENT); 

if (sqlite3_step(insert_statement) == SQLITE_DONE) { 
    // code if all ok 
} else { 
    NSAssert1(NO, @"Error: failed to insert into the database with message '%s'.", sqlite3_errmsg(database)); 
} 

sqlite3_reset(insert_statement); 
sqlite3_finalize(insert_statement); 
相關問題