How to enable Foreign Key constraint in SQLITE with Objective C

给你一囗甜甜゛ 提交于 2019-12-10 21:19:10

问题


Today I noticed that Foreign key constraint on my SQLite table does not work. After reading on Stack Overflow, I found out that this should be enabled. So, I was looking for code snippet for doing that. So far, I could only find this:

[self.db executeUpdate:@"PRAGMA foreign_keys=ON"];

But this does not seem to work for me, as compiler always complains. I saw people use this line for FMDatabase type (I don't even know what is it). So, how do I enable foreign key constraint, if I open database connection like this:

- (void) openDatabase
{
    const char* databaseFile = [[self pathToDatabaseFile:@"readlater.sql"] UTF8String];
    sqlite3 *connection;
    if (sqlite3_open(databaseFile, &connection) != SQLITE_OK) {
        return;
    }
    self.db = connection;
}

Or should it be done while creating tables? Thank you.


回答1:


When you are using the SQLite C API directly, you must also use a C function to execute SQL commands:

sqlite3_exec(connection, "PRAGMA foreign_keys = on", NULL, NULL, NULL);


来源:https://stackoverflow.com/questions/24329379/how-to-enable-foreign-key-constraint-in-sqlite-with-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!