Create a Database with ADO.NET

PDF for offline use
Sample Code:

Let us know how you feel about this

Translation Quality


0/250

This recipe will demonstrate how to create an SQLite database with ADO.NET.

Recipe

Xamarin.iOS has an ADO.NET implementation of SQLite inside the assembly Mono.Data.SQLite

  1. Add a reference to System.Data and to Mono.Data.SQLite:

  1. To create a new database use the SqliteConnection class and call the static CreateFile method with the path to the database as a parameter, as shown in the following snippet:
var documents = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var pathToDatabase = Path.Combine(documents, "db_adonet.db");
SqliteConnection.CreateFile(pathToDatabase);
  1. To create the schema for the SQLite database, create and execute DDL commands against an SQLite database connection. This snippet will create a new table called People:
var connectionString = String.Format("Data Source={0};Version=3;", pathToDatabase);
using (var conn= new SqliteConnection(connectionString))
{
    conn.Open();
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "CREATE TABLE People (PersonID INTEGER PRIMARY KEY AUTOINCREMENT , FirstName ntext, LastName ntext)";
        cmd.CommandType = CommandType.Text;
        cmd.ExecuteNonQuery();
    }
}

When the button is pushed, a new database and table is created, and the user is notified:

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.