简体   繁体   English

UWP C#应用程序连接到现有SQLite文件

[英]UWP C# app connecting to existing SQLite file

All of the tutorials that exist discussing how to incorporate SQLite into a Universal Windows Platform (UWP) app discuss the need to create database tables based upon a model. 现有的所有讨论如何将SQLite集成到通用Windows平台(UWP)应用程序的教程都讨论了基于模型创建数据库表的需求。 Is it possible to incorporate an existing SQLite file into a new application and associate an existing table to a class model. 是否可以将现有的SQLite文件合并到新的应用程序中,并将现有的表与类模型相关联。

For instance, there are very good tutorials such as this that forces the creation of a database table in order to establish the mapping of database table to data model. 举例来说,有非常好的教程,如迫使以建立数据库表的映射到数据模型的数据库表的创建。 What if I already have an existing table that I want to query against? 如果我已经有要查询的现有表怎么办?

I could not get the existing table to be recognized by manipulating my data model to match it. 我无法通过操作数据模型使其匹配来识别现有表。

Here's what I did as a work around: I exported my SQLite content to a JSON file, created a data model within my app to match the SQLite table, used the cited tutorial code to create a new table in the app binding it to the data model, and then read in the JSON file creating new instances of the data model and pushing them into the database via the insertOrReplace method. 解决方法如下:我将SQLite内容导出到JSON文件,在我的应用程序中创建了一个数据模型以匹配SQLite表,使用引用的教程代码在应用程序中创建了一个将其绑定到数据的新表。模型,然后读入JSON文件以创建数据模型的新实例,然后通过insertOrReplace方法将其推入数据库。 Now that this was done once, I have the database running the way I need it to for the app. 既然已经完成了一次,我就可以按照应用程序所需的方式运行数据库。

//Step 1 : //Get the Path of the database for example : //步骤1://获取数据库的路径,例如:

  string path = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path,
                     "ExsistingDatabase.sqlite");
                conn = new SQLite.Net.SQLiteConnection(new
                   SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path);

// Step 2: Query your database tables for example : //步骤2:例如查询您的数据库表:

using (conn = new SQLite.Net.SQLiteConnection(new SQLite.Net.Platform.WinRT.SQLitePlatformWinRT(), path))
            {
                var result = conn.Query<ObjectModel>(@"Select * From TableName");
            }

Here ObjectModel is the View Model you need in output. 在这里,ObjectModel是您需要在输出中使用的视图模型。 It could be any object. 它可以是任何对象。
Hope this helps Cheers 希望这对干杯有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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