2016-09-20 62 views
0

我正在嘗試使用Objective-c在Xcode中創建SQLite數據庫,但我在創建表時遇到問題。我相信我的插入功能是正確的,但是當我嘗試運行它時,出現以下錯誤:在Objective-C中創建SQLite數據庫時出錯Error

2016-09-20 09:39:31.612測試[58546:5169036]無法準備語句: :用戶

我的代碼在這裏。如果知道我可能做錯了,請告訴我。謝謝!

[super viewDidLoad]; 
//do any addtional setup after view load, typically from nib 
NSString *docsDir; 
NSArray *dirPaths; 

//gets the directory 
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
docsDir = dirPaths[0]; 

//Build path to keep database 
_databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"Users.db"]]; 
NSFileManager *filemgr = [NSFileManager defaultManager]; 

    if([filemgr fileExistsAtPath:_databasePath] == NO) { 
    const char *dbPath = [_databasePath UTF8String]; 

    if(sqlite3_open(dbPath, &_DB) == SQLITE_OK) { 
     char *errorMessage; 
     const char *sqlStatement = "CREATE TABLLE IF NOT EXIST Users (Username TEXT PRIMARY KEY, PASSWORD TEXT, EMAIL TEXT, null PHONE TEXT, null WINS INTEGER, null LOSSES INTEGER, null BALANCE DECIMAL INTEGER"; 

     if(sqlite3_exec(_DB, sqlStatement, NULL, NULL, &errorMessage) != SQLITE_OK) { 
      //below creates a popup success message if necessary 
      UIAlertController * alert= [UIAlertController 
              alertControllerWithTitle:@"Success" 
              message:@"Table created" 
              preferredStyle:UIAlertControllerStyleAlert]; 

      UIAlertAction* ok = [UIAlertAction 
           actionWithTitle:@"OK" 
           style:UIAlertActionStyleDefault 
           handler:^(UIAlertAction * action) 
           { 
            [alert dismissViewControllerAnimated:YES completion:nil]; 

           }]; 

      [alert addAction:ok]; 
      [self presentViewController:alert animated:YES completion:nil]; 
     } 
     sqlite3_close(_DB); 
    } 
    else { 
     //below creates a popup error message if necessary 
     UIAlertController * alert= [UIAlertController 
             alertControllerWithTitle:@"Error" 
             message:@"Unable to create table" 
             preferredStyle:UIAlertControllerStyleAlert]; 

     UIAlertAction* ok = [UIAlertAction 
          actionWithTitle:@"OK" 
          style:UIAlertActionStyleDefault 
          handler:^(UIAlertAction * action) 
          { 
           [alert dismissViewControllerAnimated:YES completion:nil]; 

          }]; 

     [alert addAction:ok]; 
     [self presentViewController:alert animated:YES completion:nil]; 
    } 
} 

}

+0

對不起有任何混淆,只是爲了澄清這是我創建數據庫的代碼。我相信這就是問題所在,因爲它表示當試圖運行我的插入時不會創建表「用戶」。 – dgelinas21

+0

你在哪裏運行?在模擬器上?嘗試做一個乾淨的生成和卸載應用程序並再次運行? 2.如果問題仍然存在,請嘗試在更新之前運行select查詢以查看是否存在表名稱? –

回答

0

請仔細覈對您的創建表的SQL,有一些問題我已經和你的SQL發現:

  1. CREATE TABLLE(應該是TABLE)
  2. 缺少閉幕SQL末尾的括號。
  3. 如果不是EXIST(應該是EXISTS)
  4. null應該在字段聲明結束時出現。例如,PHONE TEXT NULL

爲什麼不嘗試使用FMDB,這是最流行的庫處理的SQLite在OC之一。而且您不需要使用低級C代碼來處理SQLite。

+0

謝謝你的幫助!我對IOS應用程序相當陌生,我會看看FMDB。 – dgelinas21