检索或读取现有SQL文件 - C#

时间:2016-05-02 03:24:43

标签: c# database sqlite win-universal-app assets

如何从现有的sqlite文件中检索或打开数据?我在资产文件夹中有一个名为kamus.sqlite的sqlite文件。

数据库有列id,word,translation。我想在listview中显示单词和翻译列。

2 个答案:

答案 0 :(得分:0)

要在UWP中使用SQLite,您需要使用一些包装器库。

阅读这篇文章:

Using SQLite on the Universal Windows Platform

这是有效的。但只有库名称被更改。从SQLite Download Page下载适用于通用Windows平台的VSIX软件包 安装和添加参考包后,您可以从NuGet包装器SQLite.Net-PCL

安装

或者您可以使用Portable Class Library for SQLite。我用过这个库。以下是如何创建表的简单示例:

using SQLitePCL;

 using (var conn = new SQLiteConnection("Storage.db"))
            {
                string sql = @"CREATE TABLE IF NOT EXISTS People (
                                            ID INTEGER NOT NULL PRIMARY KEY,
                                            FirstName NVARCHAR(50),
                                            LastName NVARCHUAR(50));";
                using (var statement = conn.Prepare(sql))
                {
                    statement.Step();
                }
            }

要插入记录运行查询:

using (var statement = conn.Prepare("INSERT INTO People (FirstName, LastName) VALUES ('John', 'Doe')"))
                {
                    statement.Step();
                }

或者您可以使用参数:

using (var statement = conn.Prepare("INSERT INTO People (FirstName, LastName) VALUES (?, ?)"))
                {
                    statement.Bind(1, "John");
                    statement.Bind(2, "Doe");
                    statement.Step();
                }

阅读行:

List<string> column=new List<string>();
using (var statement = conn.Prepare("SELECT LastName, FirstName FROM People WHERE FirstName='John'"))
    {
       while (statement.Step() == SQLiteResult.ROW)
        {
   // here you can add value into collection for example
column.Add(statement[0]); // statement[0] - is value of first column
        }
    }

答案 1 :(得分:0)

以下是使用sqlite-net-pcl NuGet套餐的方法:

  • 将软件包安装到您的项目中。

    Install-Package sqlite-net-pcl
    
  • 创建与数据库表对应的类:

    // the name of the class must match the name of your database table
    // the names of properties must match your column names
    public class Localization 
    {
        [PrimaryKey]
        public int Id { get; set; }
        public string Word { get; set; }
        public string Translation { get; set; }
    }
    
  • 将表格中的所有数据加载到列表中:

        using (var connection = new SQLiteConnection(Path.Combine(Package.Current.InstalledLocation.Path, @"Assets\kamus.sqlite")))
        {
            var records = connection.Table<Localization>().ToList();
        }
    
  • 根据需要使用列表,例如将其绑定到ListView