将SQLite窗体应用程序迁移到通用Windows应用程序(C#)

问题描述:

我制作了一个连接到本地创建的SQLite数据库的Windows窗体应用程序。这是一个非常简单的应用程序,主要是选择并插入数据库。 我有一个类来检查这样的数据库是否存在,如果不存在,它创建它。我还添加了一些执行查询等的方法。将SQLite窗体应用程序迁移到通用Windows应用程序(C#)

现在,在Windows窗体(或控制台应用程序)的连接是非常简单的:

SQLiteConnection conn = new SQLiteConnection("Data Source=sampleDB.sqlite;Version=3;"); 
    conn.Open(); 
    //Assume that i created table Person(int ID, string NAME) 
    string sql = "select * from Person"; 
    SQLiteCommand command = new SQLiteCommand(sql, conn); 
    SQLiteDataReader reader = command.ExecuteReader(); 

    while(reader.Read()){ 
     Console.WriteLine(reader["ID"] + " | " + reader["NAME"]); 
    } 
    conn.Close(); 

现在,我试图迁移我的应用程序从Windows窗体通用的Windows应用程序。我做 的第一件事,我看到System.Data.SQLite.dll不适用于这样的应用程序,所以我SQLite.Net-PCL安装SQLite,让通用Windows平台,一起

但现在的问题是,我不知道如何像以前那样将查询作为字符串传递。 所有我遇到的是,我要创建一流的人与标识和名称的属性,然后写些这样的:

SQLitePlatformWinRT sqlitePlatform = new SQLitePlatformWinRT(); 
    var db = new SQLiteConnection(sqlitePlatform, "sampleDB.sqlite"); 
    db.CreateTable<Person>(); 

    db.Insert(new Person(ID_PERSON, NAME_PERSON)); 

有什么办法,用旧的方式(如Windows窗体)在通用Windows应用程序? IE:

//Instead of using this: 
    db.Insert(new Person(ID_PERSON, NAME_PERSON)); 
    //I want to use this: 
    SQLiteCommand command = new SQLiteCommand("insert into Person ...", conn); 
    command.ExecuteNonQuery(); 

一种可能的方式是使用Portable Class Library for SQLite,它支持SQL查询字符串,就像你在Windows窗体中使用了什么。我们可以使用这个库而不是SQLite.Net-PCL。

要使用此库,我们可以安装它形成NuGet,然后使用它像以下:

using (var connection = new SQLitePCL.SQLiteConnection("sampleDB.sqlite")) 
{ 
    using (var statement = connection.Prepare(@"select * from Person")) 
    { 
     while (statement.Step() == SQLitePCL.SQLiteResult.ROW) 
     { 
      //TODO. For example 
      //Gets the value of the specified column by the column name. 
      var Id = (long)(statement["Id"]); 
      var Name = (string)statement["Name"]; 

      //Gets the value of the specified column by the column ordinal. 
      //var Id = (long)(statement[0]); 
      //var Name = (string)statement[1]; 
     } 
    } 
} 

欲了解更多信息,你可以参考这个博客:The new Portable Class Library for SQLite。尽管本文适用于Windows 8.1,但它也适用于UWP应用程序。

+0

你能否也请在TODO部分添加如何使用让我们说来自表Person的Name属性? –

+0

即在我使用reader [“Name”]获取该属性之前。我现在如何使用它? –

+0

@MihaJamsek为了读取查询返回的记录,我们需要以类似[SqlDataReader](https://msdn.microsoft.com/en-us/library/system.data)的方式遍历行。 sqlclient.sqldatareader(v = vs.110).aspx)Class。在这里,我们可以通过列序号或列名称来获取指定列的值。由于此方法得到“Object”类型的结果,因此可能需要将其转换为列的实际类型。例如,请参阅我更新的答案。 –