How to insert data into a SQLite database in iPhone

前端 未结 4 446
南笙
南笙 2020-12-17 04:30

I am new to iPhone development. I want to insert certain data into my database and retrieve it and display it in a table. I have created Database data.sqlite wi

4条回答
  •  南笙
    南笙 (楼主)
    2020-12-17 05:10

    You basically have two recommended options (and using the C class is not one of them). FMDB is used by many any developers as a wrapper to Sqlite. http://code.google.com/p/flycode/source/browse/trunk/fmdb FMDB is lightweight and pretty easy to use.

    Here is an example call:

    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"mysqlite.db"];    
    appSettings.dao = [FMDatabase databaseWithPath:path];
    FMResultSet *rs = [[appSettings dao] executeUpdate:@"SELECT * FROM mytable"];
    while ([rs next]){
      // do stuff ...
    }
    

    This assumes am ApplicationSettings instance inside your AppDelegate .m file.

    ApplicationSettings *appSettings = [ApplicationSettings sharedApplicationSettings];
    

    Inserts are easy too:

    sql = [NSString stringWithFormat:@"INSERT INTO table (intCol1, strCol2) VALUES ('%d','%@')", myObj.theNumber, myObj.theString];
    [appSettings.dao executeUpdate:sql];
    

    The other option is to use Core Data (available as of SDK 3.0). Core Data is meant to be quite fast and optimized, although it does limit you from doing non-standard stuff. Although it can lead to slower SQL queries unless you give due consideration to how you use it.

    There's a tutorial on the iPhone Dev Center here

提交回复
热议问题