我的Objective C代码和SQLite实现存在问题。 if子句中的错误行为NSAsset
,即注释掉。这是代码:
-(void) createTable: (NSString *) tableName
withField1: (NSString *) field1
withField2: (NSString *) field2
withField3: (NSString *) field3
withField4: (NSString *) field4
{
char *err;
NSString *sql= [NSString stringWithFormat:
@"CREATE TABLE IF NOT EXIST '%@' ( '%@ "
"TEXT PRIMARY KEY, '%@' INTEGER, '%@' INTEGER, '%@' TEXT);",
tableName, field1, field2, field3, field4];
if (sqlite3_exec(db, [sql UTF8String], NULL, NULL, &err)
!= SQLITE_OK) {
sqlite3_close(db);
// NSAssert(0, @"Could not create table");
}else{
NSLog(@"table create");
}
}
-(NSString *) filePath{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask,YES);
return [[paths objectAtIndex:0]stringByAppendingPathComponent:@"bp.sql"];
}
-(void)openDB{
if (sqlite3_open([[self filePath] UTF8String], &db) !=SQLITE_OK){
sqlite3_close(db);
NSAssert(0, @"Database failed to open");
}else{
NSLog(@"Database open");
}
}
错误信息:
*** Assertion failure in -[MainViewController createTable:withField1:withField2:withField3:withField4:], /Users/Modius/X-Code 4/BPApp/BPApp/MainViewController.m:32
2013-01-18 11:38:07.772 BPApp[58857:c07] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not create table'
*** First throw call stack:
(0x2090012 0x119de7e 0x208fe78 0xc33f35 0x20a0 0x243a 0x1c6817 0x1c6882 0x115a25 0x115dbf 0x115f55 0x11ef67 0xe2fcc 0xe3fab 0xf5315 0xf624b 0xe7cf8 0x1febdf9 0x2013f3f 0x201396f 0x2036734 0x2035f44 0x2035e1b 0xe37da 0xe565c 0x1c3d 0x1b65 0x1)
libc++abi.dylib: terminate called throwing an exception
更新:这里是完整的日志输出:
2013-01-18 12:18:14.456 BPApp[59854:c07] Database open
2013-01-18 12:18:14.458 BPApp[59854:c07] *** Assertion failure in -[MainViewController createTable:withField1:withField2:withField3:withField4:], /Users/Modius/X-Code 4/BPApp/BPApp/MainViewController.m:31
2013-01-18 12:18:14.460 BPApp[59854:c07] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Could not create table'
*** First throw call stack:
(0x2090012 0x119de7e 0x208fe78 0xc33f35 0x20a0 0x243a 0x1c6817 0x1c6882 0x115a25 0x115dbf 0x115f55 0x11ef67 0xe2fcc 0xe3fab 0xf5315 0xf624b 0xe7cf8 0x1febdf9 0x1febad0 0x2005bf5 0x2005962 0x2036bb6 0x2035f44 0x2035e1b 0xe37da 0xe565c 0x1c3d 0x1b65 0x1)
libc++abi.dylib: terminate called throwing an exception
(lldb)
答案 0 :(得分:1)
NSString *sql= [NSString stringWithFormat:
@"CREATE TABLE IF NOT EXIST '%@' ( '%@ "
"TEXT PRIMARY KEY, '%@' INTEGER, '%@' INTEGER, '%@' TEXT);",
tableName, field1, field2, field3, field4];
您在第一个字段名称后缺少单引号。
(请注意,在SQL中,表/字段名称应使用双引号引用; SQLite仅接受单引号以与MySQL兼容。)
答案 1 :(得分:0)
尝试将其格式化为:
@"CREATE TABLE IF NOT EXIST '%@' ( '%@' TEXT PRIMARY KEY, '%@' INTEGER, '%@' INTEGER, '%@' TEXT);"
答案 2 :(得分:0)
修复sql语句以读取EXISTS而不是EXIST。