Search code examples
iphonesqliteinsert-query

how can I insert value into my sqlite3 database table?


I am writing a simple query as below

const char *sql = "insert into abc(name) values ('Royal')";

and this will insert each time 'Royal' into my 'name', so now I want to take input from user each time as names of hotel and wants to save them instead of 'Royal', so what should I do?

If you are not clear to my question, you may as me again,,,,,


Solution

  • you need to connect to a database

    - (sqlite3 *)database {
        if (nil == db) {
            NSString *path = <path to your database>;
            int res = sqlite3_open([path UTF8String], &db);
            if (res != SQLITE_OK){
                // handle the error.
                db = nil;
                return nil;
            }
        }
        return db;
    }
    

    then you can call this with the query

        -(void)executeQuery:(NSString *)query{
    
    
            sqlite3_stmt *statement;
    
            if (sqlite3_prepare_v2([self database], [query UTF8String], -1, &statement, NULL) == SQLITE_OK) {
    
                sqlite3_step(statement);
    
            }else{
                // handle the error.
            }
    
            sqlite3_finalize(statement);
        }
    
    -(void)dealloc {
        //close database connection
        sqlite3_close(db);
        db = nil;
        [super dealloc];
    }