Search code examples
iosiphoneios7ios5ios6

How to retrieve data from sqlite manager


I created database and also created table in that by using sqlite manager(mozilla).Now i want to retrieve that data into my iOS application.How can i do with programatically. Can you please any one help me how to do that. Thank you.


Solution

  • Use something like this:

    import:

    #import "sqlite3.h"
    

    CHECK IF DB EXISTS:

    NSString *docsDir;
    NSArray *dirPaths;
    NSString *databasePath;
    sqlite3 *DB;
    
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    
    docsDir = [dirPaths objectAtIndex:0];
    databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"YourDbName.sqlite"]]; //put your db name here
    
    NSFileManager *filemgr = [NSFileManager defaultManager];
    
    if ([filemgr fileExistsAtPath: databasePath ] == NO)
    {
        const char *dbpath = [databasePath UTF8String];
    
        if (sqlite3_open(dbpath, &DB) == SQLITE_OK)
        {
            char *errMsg;
            const char *sql_stmt = "CREATE TABLE IF NOT EXISTS YourTable (Value INTEGER PRIMARY KEY, column TEXT)";
    
    
            if (sqlite3_exec(DB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
            {
    
            }
    
            sqlite3_close(DB);
    
        }
    }
    

    Get DB Values:

        const char *dbpath = [databasePath UTF8String];
            sqlite3_stmt    *statement;
    
    
            if (sqlite3_open(dbpath, &DB) == SQLITE_OK)  //News is a sqlite variable initialized like this: sqlite3* News;
            {
                NSString *querySQL = [NSString stringWithFormat: @"SELECT * FROM YourDBName"];
    
                const char *query_stmt = [querySQL UTF8String];
    
                if (sqlite3_prepare_v2(DB, query_stmt, -1, &statement, NULL) == SQLITE_OK)
                {
                    while(sqlite3_step(statement) == SQLITE_ROW)
                    {
                        NSString* example; //example variable to assign data from db
    
                        example = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)]; //change the 0 to 1,2,3.... for every column of your db
    
                    }
    
    
                    sqlite3_finalize(statement);
                }
                sqlite3_close(DB);
            }