0

I'm using an sqlite database in my iOS app directly, without taking advantage of Core Data. When the app is launched, I need it to insert several sets of table rows of considerable amount of data that will be needed during the usage of the app and that are fixed sets of data (for example, I have a database table for a list of countries the user could choose in the app). I've those data insertions in an .sql file in the app and, since I need this data to be available in the database from the very first time the user installs and launches the app, I wrote a method that firstly copies the database to Documents, and then reads the file and performs the database insertions, and I call this method in application:didFinishLaunchingWithOptions:.

However, I'm finding that performing a lot of insertions is really a slow operation. I proceed this way:

+ (void)insertFileContent:(NSString *)fileContent intoDatabase:(sqlite3 *)database
{
   NSArray *lines = [fileContent componentsSeparatedByString:@"\r\n"];

   for (NSString *line in lines) {
      const char *sqlStatement = [line UTF8String];
      sqlite3_stmt *compiledStatement;

      if (sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {

        if(sqlite3_step(compiledStatement) == SQLITE_DONE) {
            // Insertion was ok
        }
        else {
            NSLog(@"%d",sqlite3_step(compiledStatement));
        }

        sqlite3_finalize(compiledStatement);
      }
   }
}

Database is opened only once before calling this method, and closed when it has returned. As I said, I have a lot of data I need to insert into database to make the app work properly, and it is taking even minutes to finish. I've been looking for a way to reduce this time significantly, but I didn't succeed.

How could I handle this? Is there a way to make this operations faster, and/or is there a way to insert data into the database at the time the user installs the app, instead of waiting til launch time?

Thanks in advance

4

1 回答 1

0

You have the transaction overhead once for each statement.

Wrap all statements into a single transaction. Execute BEGIN/END manually, or just write them into your .sql file.

于 2013-09-08T12:01:43.953 回答