Julien Pierre
Julien Pierre

Reputation: 467

Monotouch - Attach Sqlite database in monotouch project and deploy to iPad

All the code samples I found so far regarding using a Sqlite database in an iPad/iPhone app use scripts to create the database once the app is deployed.

But is it possible to create a database in monotouch, build the structure, even pre-populate it with data and deploy it along with iPad app?

If so, what is the location of the database, How do I build the Sqlite Connection? At the moment I use the following:

new SqliteConnection("Data Source=" + DatabasePath);

Where

public static String DatabasePath {
    get {
        string documents = Environment.GetFolderPath (Environment.SpecialFolder.Personal);
        return Path.Combine (documents, "MyDB.db");
    }
}

Upvotes: 1

Views: 2299

Answers (2)

Julien Pierre
Julien Pierre

Reputation: 467

For people using Monotouch, this is how I sorted this issue:

  1. Created the Sqlite database with sqliteman
  2. In monodevelop, right-click on the Project > Add > Add Files
  3. Choose the sqlite db created and click Open
  4. Click on Copy on the warning dialog
  5. Right click on the database you've just added > Build Action > Content

Then all you have to do is to create a simple method to copy the database to a destination folder, like Documents:

public static void CopyDatabase(String destinationPath)
{
    String path = NSBundle.MainBundle.PathForResource("MyDB", "db");
    File.Copy(path, destinationPath);
}

Where destinationPath in my case is the path specified above in the question: Here . Obviously, in production you'd have to have some sort of mechanism to check whether the db does not already exists, so that you don't overwrite the database file.

Hope it helps.

Upvotes: 2

slycrel
slycrel

Reputation: 4285

You could pre-build your database, copy it into the app bundle, and (as long as it is read-only) you could access it directly from your app's bundle whenever you want. If you need write access you could copy your pre-built file to a different directory and then modify it from there.

Upvotes: 2

Related Questions