2012-06-29 108 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()