0

我正在尝试链接 sqlite3,创建表并插入数据,但出现此错误:

'NSInternalInconsistencyException', reason: 'Error creating table: near "4": syntax error' *** First throw call stack:(0x15ad022 0x173ecd6 0x1555a48 0xa852cb 0x2bea 0x273a 0x1b5a1e 0x114401 0x114670 0x114836 0x11b72a 0x2415 0xec386 0xed274 0xfc183 0xfcc38 0xf0634 0x1497ef5 0x1581195 0x14e5ff2 0x14e48da 0x14e3d84 0x14e3c9b 0xecc65 0xee626 0x20d2 0x2045 0x1)

编码:

- (void) openDBcreateTable {
if (sqlite3_open([[self filePath]UTF8String], &db) != SQLITE_OK) {
    sqlite3_close(db);
    NSAssert(0, @"Failed to open database");
}
//create table named QUESTIONBANK
NSString *createSQL = @"CREATE TABLE IF NOT EXISTS QUESTIONBANK(ROW INTEGER PRIMARY KEY, QUESTION TEXT, ANSWER TEXT, CHOICE1 TEXT, CHOICE2 TEXT, CHOICE3 TEXT, CHOICE 4 TEXT, USERANSWER TEXT);";

char *errorMsg1;

if (sqlite3_exec(db, [createSQL UTF8String], NULL, NULL, &errorMsg1) != SQLITE_OK) {
    sqlite3_close(db);
    NSAssert(0,@"Error creating table: %s", errorMsg1);
}

for (int k = 1; k < 11; k++) {
    NSMutableArray *questionBlocks = [self pullDataFromSomeWhere];
    NSString *question = [NSString stringWithFormat:[questionBlocks objectAtIndex:0]];
    NSString *answer = [NSString stringWithFormat:[questionBlocks objectAtIndex:1]];
    NSString *choice1 = [NSString stringWithFormat:[questionBlocks objectAtIndex:2]];
    NSString *choice2 = [NSString stringWithFormat:[questionBlocks objectAtIndex:3]];
    NSString *choice3 = [NSString stringWithFormat:[questionBlocks objectAtIndex:4]];
    NSString *choice4 = [NSString stringWithFormat:[questionBlocks objectAtIndex:5]];

    char *update = "INSERT OR REPLACE INTO QUESTIONBANK(ROW,QUESTION,ANSWER,CHOICE1,CHOICE2,CHOICE3,CHOICE4)VALUES(?,?,?,?,?,?,?);";


    sqlite3_stmt *stmt;

    if (sqlite3_prepare_v2(db, update, -1, &stmt, nil) == SQLITE_OK) {
        sqlite3_bind_int(stmt, 1, k);
        sqlite3_bind_text(stmt, 2, [question UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 3, [answer UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 4, [choice1 UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 5, [choice2 UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 6, [choice3 UTF8String], -1, NULL);
        sqlite3_bind_text(stmt, 7, [choice4 UTF8String], -1, NULL);

    }
    if (sqlite3_step(stmt) != SQLITE_DONE) {
        NSAssert(0,@"Error updating table");
    }
    sqlite3_finalize(stmt);
}
sqlite3_close(db);}

我也非常有信心还有其他错误,因为我还是 sqlite 3 的新手。当我们在这里时,我可以在 sqlite3 中使用任何“VARCHAR”、“BLOB”等(如 MySQL)吗?

4

2 回答 2

0

删除 create table 语句中的虚假“4”:

... CHOICE 4 TEXT ...

应该:

... CHOICE TEXT ...

错误消息是不言自明的。

于 2012-04-29T14:31:31.827 回答
0

关于您的数据类型问题,我认为SQLite 文档清楚地解决了这个问题。最重要的是,SQLite 的数据类型有限,并且它不强制数据列的类型(因此您可以将任何数据类型存储在任何列中)。没有明确的 VARCHAR 数据类型。

于 2012-04-29T15:28:13.417 回答