【问题标题】:Migrate SQLite windows forms app to universal windows app (C#)将 SQLite windows 窗体应用程序迁移到通用 windows 应用程序 (C#)
【发布时间】:2016-10-03 12:49:47
【问题描述】:

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

现在,在 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 窗体 迁移到 Universal Windows 应用程序。 我做的第一件事是,我发现 System.Data.SQLite.dll 对这样的应用程序无效,所以我安装了 SQLite for Universal Windows Platform SQLite.Net-PCL

但现在的问题是我不知道如何像以前那样将查询作为字符串传递。 我遇到的只是我必须创建具有 Id 和 Name 作为属性的类 Person,然后编写如下内容:

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

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

有什么方法可以在通用 Windows 应用程序中使用旧方式(如在 Windows 窗体中)? 即:

    //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(); 

【问题讨论】:

    标签: c# winforms sqlite windows-10-universal


    【解决方案1】:

    一种可能的方法是使用Portable Class Library for SQLite,它支持 Sql Query String,就像您在 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 应用。

    【讨论】:

    • 您能否在 TODO 部分中添加您将如何使用表 Person 中的 Name 属性?
    • 即在我使用 reader["Name"] 获取该属性之前。我现在如何使用它?
    • @MihaJamsek 要读取查询返回的记录,我们需要以类似于SqlDataReader 类的方式遍历行。在这里,我们可以通过列序号或列名来获取指定列的值。由于此方法得到Object 类型的结果,您可能需要将其转换为列的实际类型。例如,请查看我的更新答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-02-19
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-18
    相关资源
    最近更新 更多