views:

611

answers:

2

I am new to iphone development.I want to insert multiple values into my sqlite3 database and display the content in the tableview.I am able to insert single row of data in to my database and retrieve it and display the data but i am not able to do with inserting multiple row of data.Here is my code...

-(void)initializeTableData{
sqlite3 *db=[DatabaseTestAppDelegate getNewDBConnection];
sqlite3_stmt *statement=nil;
sqlite3_stmt *statement1=nil;

if (insert_MyObj_statement == nil)
{
    const char *sql2="DELETE FROM user";
    sqlite3_prepare_v2(db, sql2, -1, &statement1, NULL);
    sqlite3_step(statement1);
    //const char *sql1 = "INSERT INTO user (id,name) VALUES ('0','ash'),('3','karna'),('2','kumar'),('5','siva')";
const char *sql1 = "INSERT INTO user (id,name) VALUES ('0','xxx')";
 int result=sqlite3_prepare_v2(db, sql1, -1, &insert_MyObj_statement, NULL);
    NSAssert1(result == SQLITE_OK, @"addMyObjectIntoDatabase: failed to prepare statement with err '%s'", sqlite3_errmsg(db));
}
 sqlite3_step(insert_MyObj_statement);

const char *sql="select * from user";
if(sqlite3_prepare_v2(db, sql, -1, &statement, NULL)!=SQLITE_OK)
    NSAssert1(0,@"error in preparing staement",sqlite3_errmsg(db));
else{
    while(sqlite3_step(statement)==SQLITE_ROW)
        [tableData addObject:[NSString stringWithFormat:@"%s",(char*)sqlite3_column_text(statement,1)]];
}
    sqlite3_finalize(statement);


}

Is there any other way to insert multiple row of data in to my table .Please help me out.Thanks.

+3  A: 

Try with sprintf statement given below, use this statement inside the loop with variable i.

sprintf(buffer,"INSERT INTO user (name) VALUES ('%s');",[[names objectAtIndex:i] UTF8String]);

Pugal Devan
And my son's name is `Robert'); DROP TABLE users; --`
KennyTM
Ah little bobby tables we call him.
marcc
A: 

SQLite doesn't support multiple-row insertion, see http://stackoverflow.com/questions/1609637/is-it-possible-to-insert-multiple-rows-at-a-time-in-an-sqlite-database.

To insert multiple rows at once, you need to issue multiple INSERT statements.

(Also, use SQLite's formatted string functions and the %q/%Q specifier to avoid SQL injection — even if that's a local database.)

(And someone will suggest you to use Core Data.)

KennyTM
you should use Core Data
kubi