2012-06-29 63 views
0

我是iPhone開發新手。我正在製作一個應用程序,使用sqlite3的數據庫。我用sqlite3管理器3.9.5創建我的表,並在appdelegete.m文件和數據庫副本中成功寫入代碼複製數據庫。如何在數據庫中插入數據並從數據庫中獲取數據

我在數據庫中插入數據,使用主鍵成功插入,但是當我從數據庫訪問數據時,它發送null,如果我打開我的數據庫並打開我的表格,它們不會顯示我在表格中輸入的數據。這裏是我的代碼插入數據並從數據庫中獲取數據。

- (IBAction)addrecord:(id)sender { 

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"ebirthdaydatabase.sqlite"]; 
     if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) { 


      const char *sqlStatement = "insert into Name(name) VALUES(?)"; 
      sqlite3_stmt *compiledStatement;     
      if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK){ 
       NSLog(@"name.text :%@",name.text); 

       sqlite3_bind_text(compiledStatement, 1, [name.text UTF8String], -1, SQLITE_TRANSIENT); 
//    ShowContactsViewController *contact = [[ShowContactsViewController alloc]init]; 
//    contact.username = name.text; 
//    [contact addarray:contact]; 

      } 

      if(sqlite3_step(compiledStatement) != SQLITE_DONE) { 
       NSLog(@"Error: %s", sqlite3_errmsg(database)); 
      } else { 
       NSLog(@"Insert into row id = %lld", sqlite3_last_insert_rowid(database)); 
      } 
      sqlite3_finalize(compiledStatement); 

     sqlite3_close(database); 
     } 

sqlite3 *database; 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"ebirthdaydatabase.sqlite"]; 

    NSLog(@"%@",path); 
    if (sqlite3_open([path UTF8String], &database) == SQLITE_OK) { 

     const char *sql = "select name from Name"; 
     sqlite3_stmt *selectstmt; 
     if(sqlite3_prepare_v2(database, sql, -1, &selectstmt, NULL) == SQLITE_OK) { 

      while(sqlite3_step(selectstmt) == SQLITE_ROW) { 

       //    NSInteger primaryKey = sqlite3_column_int(selectstmt, 0); 
       //    Coffee *coffeeObj = [[Coffee alloc] initWithPrimaryKey:primaryKey]; 
       ShowContactsViewController *contact=[[ShowContactsViewController alloc]init]; 

       char *localityChars =(char *)sqlite3_column_name(selectstmt, 0); 

       if (localityChars ==NULL) 
        contact.username = nil; 
       else 
        contact.username = [NSString stringWithUTF8String: localityChars]; 

       //contact.username = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 1)]; 
       NSLog(@"%@",username); 

       [showcontact addObject:contact]; 
      } 
     } 
    } 

回答

0

sqlite3_column_name()函數將返回列的名稱,而不是內容。您需要改爲sqlite3_column_text()