简体   繁体   中英

Xamarin SQLite Database Check

I am new to Xamarin. I want to confirm if the database is created and if the data is being inserted to the SQLite database. Thank you for the help

Questions:
1. How to check if database exist/created or not?
2. How to check if the user are inserted successfully or it failed?
3. Where do these file go in my phone?

Below is my code:

App.xaml.cs

using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using TBSMobileApplication.Views;
using TBSMobileApplication.Data;

[assembly: XamlCompilation (XamlCompilationOptions.Compile)]
namespace TBSMobileApplication
{
    public partial class App : Application
    {
        static TokenDatabaseController tokenDatabase;
        static UserDatabaseController userDatabase;

        public App ()
        {
            InitializeComponent();

            MainPage = new LoginPage();
        }

        protected override void OnStart ()
        {
            // Handle when your app starts
        }

        protected override void OnSleep ()
        {
            // Handle when your app sleeps
        }

        protected override void OnResume ()
        {
            // Handle when your app resumes
        }

        public static UserDatabaseController UserDatabase
        {
             get
            {
                if(userDatabase == null)
                {
                    userDatabase = new UserDatabaseController();
                }

                return userDatabase;
            }
        }

        public static TokenDatabaseController TokenDatabase
        {
            get
            {
                if (tokenDatabase == null)
                {
                    tokenDatabase = new TokenDatabaseController();
                }

                return tokenDatabase;
            }
        }
    }
}

LoginPage.xaml.cs (Basically this is my Code behind in my login page)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TBSMobileApplication.Models;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace TBSMobileApplication.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class LoginPage : ContentPage
    {
        public LoginPage ()
        {
            InitializeComponent ();
        }

        void LoginProcedure(object sender, EventArgs e)
        {
            User user = new User(entUser.Text, entPassword.Text);
            if (user.CheckInformation())
            {
                //DisplayAlert("Login Message", "Login Success", "Ok");
                try
                {
                    App.UserDatabase.SaveUser(user);
                    DisplayAlert("Database Message", "User Saved", "Ok");
                }
                catch(Exception ex)
                {
                    DisplayAlert("Message", ex.Message, "Ok");
                }

            }
            else
            {
                DisplayAlert("Login Message", "Login Failed", "Ok");
            }
        }
    }
}

ISQLite.cs (This is where you get the connection to the database)

using SQLite;
using System;
using System.Collections.Generic;
using System.Text;

namespace TBSMobileApplication.Data
{
    public interface ISQLite
    {
        SQLiteConnection GetConnection();
    }
}

User.cs (This is where the parameters of the User table)

using SQLite;
using System;
using System.Collections.Generic;
using System.Text;

namespace TBSMobileApplication.Models
{
    public class User
    {
        [PrimaryKey, AutoIncrement]
        public int ContactID { get; set; }
        [Unique]
        public string UserID { get; set; }
        public string UserPassword { get; set; }

        public User() { }
        public User(string Username, string Password)
        {
            this.UserID = Username;
            this.UserPassword = Password;
        }

        public bool CheckInformation()
        {
            if(!this.UserID.Equals("") || !this.UserPassword.Equals(""))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
    }
}

SQLite_Android.cs (This is where I created the database)

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using TBSMobileApplication.Data;
using TBSMobileApplication.Droid.Data;
using Xamarin.Forms;

[assembly: Dependency(typeof(SQLite_Android))]

namespace TBSMobileApplication.Droid.Data
{
    public class SQLite_Android : ISQLite
    {
        public SQLite_Android() { }
        public SQLite.SQLiteConnection GetConnection()
        {
            var DBFileName = "backend.db3";
            string DocumentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
            var path = Path.Combine(DocumentPath, DBFileName);
            var conn = new SQLite.SQLiteConnection(path);

            return conn;
        }
    }
}

UserDatabaseController.cs (This is where I control User table like adding, deleting or getting data from User table)

using SQLite;
using System;
using System.Collections.Generic;
using System.Text;
using TBSMobileApplication.Models;
using Xamarin.Forms;

namespace TBSMobileApplication.Data
{
    public class UserDatabaseController
    {
        static object locker = new object();

        SQLiteConnection database;

        public UserDatabaseController()
        {
            database = DependencyService.Get<ISQLite>().GetConnection();
            database.CreateTable<User>();
        }

        public User GetUser()
        {
            lock (locker)
            {
                if(database.Table<User>().Count() == 0)
                {
                    return null;
                }
                else
                {
                    return database.Table<User>().First();
                }
            }
        }

        public int SaveUser(User user)
        {
            lock (locker)
            {
                if (user.ContactID != 0)
                {
                    database.Update(user);
                    return user.ContactID;
                }
                else
                {
                    return database.Insert(user);
                }
            }
        }

        public int DeleteUser(int contactid)
        {
            lock (locker)
            {
                return database.Delete<User>(contactid);
            }
        }
    }
}

Starting with part 3 of your question - where is the database file? - it's here:

var DBFileName = "backend.db3";
string DocumentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);

That equates to:

/data/data/[your.package.name]/files/backend.db3

For the first part of your question, to check whether the database has been created, just check whether the file exists:

    public static bool DBExists()
    {
        string DocumentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        var path = Path.Combine(DocumentPath, "backend.db3");
        return File.Exists(path);
    }

Accessing the file there is somewhere between difficult and impossible without a rooted device. You're not supposed to be able to access files there - only your app can access them. It's a safety measure.

Your application doesn't have any trouble accessing the database file, though, so you can implement a method in your application to copy it somewhere more accessible (eg the Downloads directory).

Put this in your Android project:

    public static void CopyDBToDownloadsDirectory()
    {
        var path = System.IO.Path.Combine(
            Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath,
            "backend.db3");
        string DocumentPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
        var safePath = Path.Combine(DocumentPath, "backend.db3");
        File.Copy(safePath, path, true);
    }

Call it to create a copy of the database you can readily access on the phone's built-in file browser.

So, for part 2 of the question, whether a transaction succeeded or failed, you can either run queries against your database in code to check, or open a copy of the database file in a GUI and browse the data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM