Posts Tagged ‘sqlite’

iPhone can’t find SQLite database but simulator can

Written by Alex on . Posted in Uncategorized

Now our company working on iPhone application to track weight. The application user SQLite database as a data source for weight values.

We tested application on iPhone simulator and it worked fine, it was no problems with opening database, reading and writing records in SQLite database.

But after deployment on iPhone device application stop working. For some reason application was not able to find database on iPhone device.  Googling and asking questions on StackOverflow did not helped, and our developer continue investigate around this issue.

And finally the problem was solved. It was small defect in our application with upper and lowercase names.

The difference between iPhone device and iPhone application was the following: iPhone cares about register of filenames, but iPhone device does not care. So the name “database.sqlite” and “Database.sqlite” was different files on iPhone device.

As we understand later it’s a normal behaviour for UNIX system, but for developers who come from Windows it’s a little bit weird behaviour.

iPhone: open connection with SQLite database

Written by Alex on . Posted in Uncategorized

To open connection with SQLite database from iPhone you need to follow the steps: At first you have to add reference to SQLite framework in Xcode project. If you using Xcode 4 go to “Target” -> “Build phases” and under “Link binary with libraries” add “libsqlite3.dylib” file. After you have reference to SQLite framework include header file at the top of your code file.

	#import <sqlite3.h>

Now you can use SQLite functions in your code.

Open connection with SQLite database

You can open connection to database using the following function

int sqlite3_open(
  const char *filename,   /* Database filename (UTF-8) */
  sqlite3 **ppDb          /* OUT: SQLite db handle */
);

SQLite API have two more function to open database, but this is the simplest. If you need to read more how to open connection from iPhone application to SQLite database refer to SQLite documentation.

Usually you have database name as a (NSString*) variable, so you have to extract UTF8 string from NSString. You can do it using UTF8String method.

This is an example from iPhone application which we recently developed:

	// databaseFullPath was defined in different place,
	// and contain path to SQLite database file
	sqlite3 *database;
    if(sqlite3_open([databaseFullPath UTF8String],
	&database) == SQLITE_OK)
    {
		// database is opened. you can read/write to database

		// do not forget to close database
		sqlite3_close(database);
	}

If sqlite3_open function returns 0 or SQLITE_OK, it means than database was found, and connection was successfully opened. Otherwise something happened during the opening. Most probably database file was not found.