2012-11-09 319 views
0

我花了几天的时间试图解决这个问题,我放弃了! 我正在做的是从用户接收输入,并将其插入数据库,如果他按下“保存”按钮。 当我运行这个代码,并按下“保存”按钮后。 1-不能退出视图(到另一个选项卡)。 2-插入没有应用!在数据库中插入SQlite错误

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


    //Copy the database from the package to the usrrs filesystem 
    if (sqlite3_open([dbPath UTF8String], &database)== SQLITE_OK) {//start if 
     NSLog(@"dataBaseOpen"); 
     const char *sqlStatement = "insert into Location (Latitude,Longitude,LocationName,Tag) VALUES (?,?,?,?)"; 
     // 
     sqlite3_stmt *compileStatement; 

     if (sqlite3_prepare_v2(database, sqlStatement, -1, &compileStatement, NULL) == SQLITE_OK) { // start if 2 
      if(SQLITE_DONE!=sqlite3_step(compileStatement)) 
      { 
      sqlite3_bind_double(compileStatement, 1, [latitudeTextField.text doubleValue]); 

      sqlite3_bind_double(compileStatement, 2, [longitudeTextField.text doubleValue]); 

      sqlite3_bind_text(compileStatement, 3, [lName.text UTF8String], -1, SQLITE_TRANSIENT); 

      sqlite3_bind_text(compileStatement, 4, [myText.text UTF8String] ,-1, SQLITE_TRANSIENT); 
      NSLog(@" successfully done"); 
      if(sqlite3_step(compileStatement) != SQLITE_DONE) { 
       NSLog(@" not done"); 
      } 
      } 

     } 
    } 

和我把的appDelegate代码在文件管理器应对:

的NSArray *路径= NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES); NSString * documentsDir = [paths objectAtIndex:0];

NSString *dbPath = [documentsDir stringByAppendingPathComponent:@"CAMAClientDB2.sqlite"]; 


NSFileManager *fileManager = [NSFileManager defaultManager]; 

BOOL success = [fileManager fileExistsAtPath:dbPath]; 

if (success) { 

    NSLog(@"we have the database"); 

} else { 

    NSLog(@"we have no database"); 

    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"CAMAClientDB2.sqlite"]; 


    BOOL moved = [fileManager copyItemAtPath:defaultDBPath toPath:dbPath error:nil]; 

    if (moved) { 
     NSLog(@"database copied"); 
    } 



} 

我错过了什么!问题是什么 !!

回答

0

对于你#2的问题: 1.你有一个额外的sqlite_step调用。您的顺序应该是:

sqlite3_prepare_v2() 
      sqlite_bind_.... 
      sqlite_bind_.... 
      for as many bind's as you need, and then 
      sqlite_step() 
  1. 如果sqlite_step仍然失败,检查返回代码,并寻求指导在文档

  2. 如果您的MacOS应用是Sandbox'd,这不会工作。目前没有办法自行更新sqlite数据库。您必须获得用户对sqlite文件所在目录的写入权限,或者必须将其放入包中(实际上是相同的东西)

+0

谢谢morejanus !!!!它运作良好 – Alaa12

+0

但NSLog打印“成功完成”,但我怎么能打开数据库,并检查行是否存在! 当我通过SQlite插件打开它时,我没有找到它!这是否意味着它是错误的? – Alaa12