2016-09-20 64 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