Powered by coANDco UK

How to get started with SQLite on the iPhone

From How2s

This is a quick tutorial on how to get started with SQLite and the iPhone:

1.) Add the /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS2.0.sdk/usr/lib/libsqlite3.dylib framework to your project in XCode

2.) Add #import <sqlite3.h> in your interface file

3.) Create a database file, see e.g. http://how2s.org/index.php/SQLite

4.) Declare 2 variables in your interface file:

sqlite3 *database;
NSString *dbPath;

5.) In the implementation, write

- (void) createTable {

	dbPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"yourdbfile.sqlite"];

	if (sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK) {
		
		NSString *createSql = @"CREATE TABLE test (text varchar(255))";
		
		if (sqlite3_exec(database, [createSql cStringUsingEncoding:NSUTF8StringEncoding], NULL, NULL, NULL) == SQLITE_OK) {
			NSLog(@"create table");
			NSString *insertSql = @"INSERT INTO test (text) VALUES('fff')";
			int testvalue = sqlite3_exec(database, [insertSql cStringUsingEncoding:NSUTF8StringEncoding], NULL, NULL, NULL);
		
			if (testvalue == SQLITE_OK) {
				NSLog(@"insert query ok");
			} else {
				NSLog(@"error code %i", testvalue);
			}
		}
	}
}

6.) How to use the SELECT query:

- (void) findRowNb {
	NSString *selectSql = @"SELECT COUNT(*) FROM test";
	sqlite3_stmt *statement;
	if (sqlite3_prepare_v2(database, [selectSql cStringUsingEncoding:NSUTF8StringEncoding], -1, &statement, NULL) == SQLITE_OK) {
		while (sqlite3_step(statement) == SQLITE_ROW) {
			int count = sqlite3_column_int(statement, 0);
			NSLog(@"row nb %i", count);
		}
	}
}

More details can be found under the SQLite Tutorial

More Links

http://www.iphonesdkarticles.com/2008/07/iphone-sdk-tutorial-using-sql-lite-part.html http://www.iphonesdkarticles.com/2008/07/iphone-sdk-tutorial-using-sql-lite-part_21.html

Please check out our sponsor, thanks to whom How2s.org is FREE: