Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 924
Sunny Ho Avatar asked Aug 15 '10 21:08

Sunny Ho


People also ask

What is an SQLite script?

Many times when you're working with a SQLite database, you'll keep all your CREATE TABLE SQL commands in a database script, which you'll then execute from your database server command line prompt. The file of database commands you execute is often referred to as a "script", or in this case, a "SQLite script".

Why do we use SQLite3?

SQLite is used to develop embedded software for devices like televisions, cell phones, cameras, etc. It can manage low to medium-traffic HTTP requests. SQLite can change files into smaller size archives with lesser metadata. SQLite is used as a temporary dataset to get processed with some data within an application.


2 Answers

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;
}
like image 188
Alpine Avatar answered Oct 28 '22 02:10

Alpine


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

like image 31
schoetbi Avatar answered Oct 28 '22 00:10

schoetbi