Xamarin Form - SqLite

Copy Below Code:

Please watch video to understand code.

    public class SqlHelper
    {
        public static string Username { get; set; }
        public static string Email { get; set; }
        public static string Language { get; set; }
        public static int CompanyID { get; set; }

        readonly SQLiteAsyncConnection database;
        public static string root = string.Empty;
        public SqlHelper()
        {
            var location = "demoDB.db2";
            location = System.IO.Path.Combine(root, location);
            database = new SQLiteAsyncConnection(location);
            database.CreateTableAsync<tblCredentials>().Wait();
        }
        public Task<int> InsertCredential(tblCredentials tbl) => database.InsertAsync(tbl);
        public Task<int> insert(tblCredentials tbl)
        {
           return database.InsertAsync(tbl);
        }
        public Task<int> UpdateCredential(List<tblCredentials> tbl) => database.UpdateAllAsync(tbl);
        public tblCredentials GetCredential() => database.Table<tblCredentials>().FirstOrDefaultAsync().Result;
        public List<tblCredentials> GetCredentialList() => database.Table<tblCredentials>().ToListAsync().Result;
        public Task<int> DeleteCredential() => database.ExecuteAsync("Delete from [tblCredentials]");
    }

    public class tblCredentials
    {
        public string Username { get; set; }
        public string Email { get; set; }
        public string Language { get; set; }
        public int CompanyID { get; set; }
    }

    public class CrudOperation
    {
        public void Delete()
        {
            var sqlH = new SqlHelper();
            sqlH.DeleteCredential();
        }
        public void Insert()
        {
            var sqlH = new SqlHelper();
            sqlH.InsertCredential(new tblCredentials
            {
                CompanyID = SqlHelper.CompanyID,
                Language = SqlHelper.Language,
                Email = SqlHelper.Email,
                Username = SqlHelper.Username,
            });
        }

        public void Update(int id)
        {
            var sqlH = new SqlHelper();
            List<tblCredentials> credentials =  sqlH.GetCredentialList();
            foreach (tblCredentials tbl in credentials)
            {

                tbl.CompanyID = (tbl.CompanyID == id) ? 1 : 2;
            }
            sqlH.UpdateCredential(credentials);
        }
    }

In Android Project: Mainacitivity.cs in oncreate method

SqlHelper.root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

In IOS Project: Appdelegate.cs in FinishedLaunching method

SqlHelper.root = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

Comments

Popular posts from this blog

Push Notifications in .NET MAUI: A Comprehensive Guide

Explore the UI libraries available for .NET MAUI at no cost.

Push Notification using Firebase in xamarin form (Android and IOS)