Sunny Ho
Sunny Ho

Reputation: 53

how to run sql script file in sqlite3 through objective-C

Here is my question, when interacting with Sqlite 3 through terminal, you can execute SQL statements stored in a txt file by executing this command:

 .read filename

Is there a way to do such thing through Objective-C code? i.e. I've got a sqlite3 db file connected in the code, and i'd like to run a script file programmatically.

Upvotes: 5

Views: 2600

Answers (2)

Alpine
Alpine

Reputation: 1357

I know this is a really old question. I just thought I'd leave the code that i used just in case someone else would find it useful

-(BOOL)execFile:(NSString*)filepath
{
    NSError* error;
    NSString* content = [NSString stringWithContentsOfFile:filepath encoding:NSUTF8StringEncoding error:&error];
    if(error)
    {
        return NO;
    }
    char* execError;
    int x = sqlite3_exec(_database, [content UTF8String], nil, nil, &execError);
    if(execError)
    {
        NSLog(@"%s", execError);
    }
    return x == SQLITE_OK;
}

Upvotes: 6

schoetbi
schoetbi

Reputation: 12846

You could forward the content of the file line by line, or in whole to the function exec

Upvotes: 2

Related Questions