简体   繁体   中英

SQLite support for Universal Windows App

I am using Xamarin Forms to develop an app and using SQlite to store the user details. Just started with windows(Windows 10). Does SQLite has support for UWP, I have referred some sites and its saying it does support. but when I am trying, the connection is always null.

The code i am using:

 public SQLite.Net.SQLiteConnection GetConnection()
 {
  var sqliteFilename = "Sample.db3";
  string path = Path.Combin(ApplicationData.Current.LocalFolder.Path, sqliteFilename);
   if (!File.Exists(path))
   {
    File.Create(path + sqliteFilename);
   }
   var plat = new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT();
   var conn = new SQLite.Net.SQLiteConnection(plat,path);

    return conn;
    }
 }

Any help or suggestion would be much appreciated.

Note: I have installed the SQLite.Net-PCL and added reference to SQLite for Universal App Platform

Inside your App.cs I have a static variable called:

public static LocalDatabase Database { get; private set; }

public App()
{   
    Database = new LocalDatabase();...
}

And then you can access your Database class on any place of your controller like: App.Database

For reference LocalDatabase class will contain:

public class LocalDatabase
{
    static readonly object locker = new object ();

    static SQLiteConnection database;

    string DatabasePath {
        get {
            const string sqliteFilename = "LocalDatabaseSQLite.db3";
#if __IOS__
            string documentsPath = Environment.GetFolderPath (Environment.SpecialFolder.Personal); // Documents folder
            string libraryPath = Path.Combine (documentsPath, "..", "Library"); // Library folder
            var path = Path.Combine (libraryPath, sqliteFilename);
#else
#if __ANDROID__
            string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
            var path = Path.Combine(documentsPath, sqliteFilename);
#else
            // WinPhone
            var path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, sqliteFilename); ;
#endif
#endif
            return path;
        }
    }

    public LocalDatabase ()
    {
        database = new SQLiteConnection (DatabasePath);

        database.CreateTable<UserSQLModel> ();

        //All your create tables...
    }
}

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