Sat
Sat

Reputation: 1626

Inserting array of value in Sqlite3 i-phone

I am trying to insert a set of values in an sqlite table using a for loop. It is inserting only one set of value. I am posting here my code:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *databasePath = [documentsDirectory stringByAppendingPathComponent:@"myDatabase.sql"];

for(int i=0;i<[arr count];i++)
{
    sqlite3 *database;

    // Open the database from the users filessytem
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
        NSLog(@"\n inserting data \n");
        sqlite3_exec(database, [[NSString stringWithFormat:@"INSERT INTO AnswerConnect VALUES('%@')",[arr objectAtindex:i] ] UTF8String], NULL, NULL, NULL);    
        //sqlite3_finalize(compiledStatement);
        sqlite3_close(database);
    }       
}

Thanks in advance.

Upvotes: 0

Views: 853

Answers (2)

Hitesh
Hitesh

Reputation: 1230

You have to first prepare a sqlite statement to insert data in table.Try this :

sqlite3_stmt *statement = nil    
const char *sql = "insert into tablename (col1,col2) Values( ?, ?)";

if(sqlite3_prepare_v2(database, sql, -1, &statement, NULL) != SQLITE_OK)
{
     NSLog(@"Error while creating add statement. '%s'", sqlite3_errmsg(database));
}

for(int i=0;i<[arr count];i++)
{
      sqlite3_bind_text(statement, 1,[[arr objectAtindex:i] UTF8String] , -1, SQLITE_TRANSIENT);

     if(SQLITE_DONE != sqlite3_step(add_statement))
     {
    NSLog(@"Error while inserting result data. '%s'", sqlite3_errmsg(database));
     }
     //Reset the add statement.
     sqlite3_reset(statement);
}

Upvotes: 1

Serhii Mamontov
Serhii Mamontov

Reputation: 4932

Don't do like that! Don't open/close SQLite connection in loop like that! Open handle to database outside from loop and than just use pointer on it. In this kind of request it's unsafe to insert format, because SQL statement may be compiled with some kind of injection code. Use sqlite3_stmt instead and bind values to it. Also if you compile only one instance of sqlite3_stmt and reuse it, this will give you better performance than compiling new statements all the time.

How many columns in each data set? Does it insert only one value from single data set like string?

Upvotes: 1

Related Questions