3

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.

2
  • The FMDatabase class is part of the FMDB library, a thin Objective-C wrapper around the SQLite C API. Using FMDB can greatly simplify your SQLite code. Commented Jun 20, 2014 at 16:31
  • @Rob, thank you for clearing this out for me. I will read look into it. Commented Jun 20, 2014 at 16:34

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Hi, thank you for your reply. Should I insert this line before each SELECT/INSERT/... statement?
What has to be done? I executed PRAGMA foreign_keys = ON; at application start, as the only statement in a transaction, and in the next transaction I execute PRAGMA foreign_keys; and it still returns 0.
@Ixx To ask a question, use the "Ask Question" button.
This answer ("call sqlite3_exec()") would not be the same as for your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.