I am completely new to SQLite and iOS. I am following a basic tutorial on how to use SQLite in iOS:
http://www.switchonthecode.com/tutorials/using-sqlite-on-the-iphone#comment-11617
In the above link, they have specified the database as:
sqlite3 *database;
int result = sqlite3_open("/myExampleDatabase.db", &database);
but when I use the above code with replacing my database name, I get an error as specified in the subsequent alertview.
My question here is, do I have to add the database file into my resource folder? If not, do I have to have my database file somewhere that is accessible to iOS?
If you want to open a sqlite database, you might want to:
Make sure you're including your database in your bundle.
Programmatically copy the database from your bundle to your documents (esp important if user will be modifying the database; if you're only reading, you could go ahead an just open the version in the bundle).
If you're running this in your simulator, you can go ahead and inspect the bundle and Documents folders if things don't go right, just to make sure everything is where it should be. You simulator's folder is something like "~/Library/Application Support/iPhone Simulator/5.1/Applications/" (replace the 5.1 with whatever version of your simulator you are using). You might have to unhide your Library folder, if you haven't already, by running the
chflags nohidden ~/Library
in aTerminal
command-line window.So, the code for getting the path of the database (and copying it to the Documents if it's not there yet), might look like:
Then, if you're doing your own sqlite calls, it would be something like:
Or, alternatively, if you're using FMDB, it would be something like:
I suggest using FMDB wrapper for SQLite: https://github.com/ccgus/fmdb
I fully support the previous answer in most cases, however:
Are you sure you have to use
sqlite3
instead ofCore Data
?There are several discussion where you can get information when to use a database wrapper (like fmdb) and when to use
Core Data
. (Speaking personally, I love to use fmdb, but it always results in more code, complexity and most of the time a worse performance)Some links to get started with
Core Data
: