Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable Foreign Key constraint in SQLITE with Objective C

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.

like image 501
sermilion Avatar asked Mar 21 '26 04:03

sermilion


1 Answers

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);
like image 54
CL. Avatar answered Mar 22 '26 17:03

CL.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!