lundi 9 novembre 2015

Difference in commands for creating a table & inserting values in a table in a sqlite database?

I have been doing sqlite program for a while in XCODE by following a tutorial. I generally write the following code while creating a table and inserting values in the database:

//For Creating a database
if ([filemgr fileExistsAtPath:finalPath]==NO)
    {
        sqlite3 *database;
        const char *dbpath=[finalPath UTF8String];
        if(sqlite3_open(dbpath,&database )==SQLITE_OK)
        {
           char *error;
            const char *chstmt="CREATE TABLE IF NOT EXIST(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT";
            //sqlite3_stmt *sqlstmt;
            if(sqlite3_exec(database,chstmt,NULL,NULL,&error)!==SQLITE_OK)

        {
            NSLog(@"failed to create table");

            }
            sqlite3_close(database);

And for inserting values into the database-

if (sqlite3_open(ch, &database)==SQLITE_OK)
    {
        NSString *query=[NSString stringWithFormat:@"INSERT INTO emp1(id,name) values (\"%@\",\"%@\")",_id.text,_name.text];
        NSLog(@"%@",query);
        const char *chstmt=[query UTF8String];
        sqlite3_stmt *sqlstmt;
        if (sqlite3_prepare_v2(database, chstmt, -1, &sqlstmt, NULL)==SQLITE_OK)
        {
            if (SQLITE_DONE==sqlite3_step(sqlstmt))
            {
                _id.text=nil;

                _name.text=nil;

                UIAlertView *alert=[[UIAlertView alloc]initWithTitle:@"success" message:@"sucessfully registered" delegate:self cancelButtonTitle:@"ok" otherButtonTitles: nil];
                [alert show];
            }
            else NSLog(@"failure");
        }
        sqlite3_finalize(sqlstmt);

    }
    sqlite3_close(database);
}

Now I do have the following questions that I don't understand- 1)Why are we not using sqlite3_prepare_v2() while creating a table.

2)Why we are not using the sqlite3_exec() while inserting in a table?

3)Difference between the above 2 functions?

Please answer my above questions ? Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire