First we need WriteExternalStorage Permission
Add a reference to System.Data and to Mono.Data.SQLite
// with Android.Graphics & Android.Environment
var docsFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments);
var pathToDatabase = System.IO.Path.Combine(docsFolder, "db_adonet.db");
SqliteConnection.CreateFile(pathToDatabase);
// without Android.Graphics & Android.Environment
using System.IO;
var docsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var pathToDatabase = Path.Combine(docsFolder, "db_adonet.db");
SqliteConnection.CreateFile(pathToDatabase);
// with try / catch
try
{
var docsFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var pathToDatabase = Path.Combine(docsFolder, "db_adonet.db");
SqliteConnection.CreateFile(pathToDatabase);
}
catch (IOException ex)
{
var reason = string.Format("The database failed to create - reason {0}", ex.Message);
Toast.MakeText(myContext, reason, ToastLength.Long).Show();
}
// using File.Exists
if (!File.Exists(pathToDatabase))
{
var reason = string.Format("The database failed to create - reason {0}", ex.Message);
Toast.MakeText(myContext, reason, ToastLength.Long).Show();
}
// create a connection string for the database
var connectionString = string.Format("Data Source={0};Version=3;", pathToDatabase);
try
{
using (var conn = new SqliteConnection((connectionString)))
{
await conn.OpenAsync();
using (var command = conn.CreateCommand())
{
command.CommandText = "CREATE TABLE People (PersonID INTEGER PRIMARY KEY AUTOINCREMENT, FirstName ntext, LastName ntext)";
command.CommandType = CommandType.Text;
await command.ExecuteNonQueryAsync();
}
}
}
catch (Exception ex)
{
var reason = string.Format("Failed to insert into the database - reason = {0}", ex.Message);
Toast.MakeText(myContext, reason, ToastLength.Long).Show();
}
References :
https://developer.xamarin.com/recipes/android/data/databases/adonet/