id | title | brief |
---|---|---|
37D84956-B056-2A95-604C-DB14A9D655FC |
Create a Database with ADO.NET |
This recipe will demonstrate how to create an SQLite database with ADO.NET. |
Xamarin.iOS has an ADO.NET implementation of SQLite inside the assembly Mono.Data.SQLite
- Add a reference to System.Data and to Mono.Data.SQLite:
- To create a new database use the
SqliteConnection
class and call the staticCreateFile
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);
- 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: