Sponser Link

Create a new database of SQLite in Xamarin forms using C Sharp

SQLite is RDMS and type of other database. But it is not client server database like other database. It is used especially when you are doing device level programming. In this tutorial, we will learn that how to create database of sqlite.

Create new project in .net using xamarin frame work, add new class named Employee.

public class Employee
    {
       [PrimaryKey,AutoIncrement]
        public int EmpID { get; set; }
        public string EmpNo { get; set; }
        public string UserName { get; set; }
        public string DeviceID { get; set; }
        public int IsActive { get; set; }
        public int IsRegister { get; set; }
    }

Here you EmpID is primary key and type is auto increment. If you don’t want auto key then you can remove the keyword of auto increment.

Add new class “Database” in your project. Name space will be used of SQLite. Add given below code in class constructor for create the database.

public Database(string dbPath)
{
   _db = new SQLiteAsyncConnection(dbPath);
   _db.CreateTableAsync().Wait();
   _db.CreateTableAsync().Wait();
   _db.CreateTableAsync().Wait();
}

Now we will create the static instance of database class and this will be create on application level. Therefore we have to go at App.xaml.cs class and write the single ton pattern for database class instance.

static Database db;

public static Database EmpDB
{
    get
    {
       if (db == null)
      {
         db = new Database(Path.Combine(Environment.GetFolderPath
             (Environment.SpecialFolder.LocalApplicationData), "Emp.db3"));
      }

     return db;
    }
 }

Now your database will be created if database does not exist when you will call any function of database class. If database will exist already then same instance will be return. Further database operations, we will discuss in next tutorial.