5

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.

2 Answers 2

6

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

Comments

2

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

5 Comments

Thanks for the reply, so, I guess that means I'll have to read the file into string myself and exec the whole lot as one big SQL statement then?
That is the only solution I see that is feasable to do. I also thought about controlling the stdin of the process and pass the command .read into it but I was not sure wather this will work. You can try it but as I said not sure if it works.
Thanks, I tried running the script in one go but it didn't work. Then I read in the file and execute line by line, bingo! Thanks again.
How did you end up doing this "line-by-line"?
@rckehoe: This only works if one line is a complete statement. Then read in one line from file and pass is to exec. Or Read the complete content of a file and pass the whole string to exec (if not too big)

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.