65.9K
CodeProject 正在变化。 阅读更多。
Home

SQLite 和 UWP

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2投票s)

2018 年 8 月 21 日

CPOL

2分钟阅读

viewsIcon

17273

downloadIcon

458

将 Sqlite 集成到您的 Visual Studio/C# 应用程序中。

引言

本文介绍了如何在您的通用 Windows 平台 (UWP) C# 应用程序中包含 Sqlite 数据库。

背景

Sqlite 是一个免费的数据库程序,可用于“轻量级”数据库应用程序。它支持事务和 SQL 调用,并且相对容易使用。将 Sqlite 集成到 UWP 应用程序中非常快速且容易;下面列出了在您的 C# UWP 应用程序中包含 Sqlite 的步骤。还包括和描述了一些简化 Sqlite 使用的公开可用类,以及一些展示如何使用这些类的示例代码。最后,还包括了有用的下载和更多信息的链接。

将 Sqlite 添加到您的解决方案

注意:这适用于 Visual Studio 2015 和 2017。

应该使用 NuGet 将 Sqlite UWP 库添加到您的解决方案中。

  1. 单击工具|NuGet 包管理器|管理解决方案的 NuGet 包… 并选择浏览
  2. 搜索 Sqlite.UWP.Native 找到后, 在解决方案中安装它。

使用 Sqlite UWP 库

两个名为 Sqlite.csSqliteAsync.cs 的文件可用于为 Sqlite UWP 库提供简单的 C# 接口。它们可以从这里下载

该站点还包含该接口的详细文档。

Sqlite.cs 文件包含一个名为 SqlConnection 的类,可用于创建和操作 Sqlite 数据库。 SqliteAsync.cs 包含一个名为 SqliteAsyncConnection 的类,用于异步数据库例程。应该将其中一个或两个文件添加到您的解决方案中,具体取决于您使用的是异步模型还是非异步模型。

这两个类都有用于连接和断开数据库连接、创建数据库以及添加、删除和更新数据库记录的方法。此外,这些类可用于执行原始 SQL 脚本。

例如,附带的文件包含调用 SqlConnection 例程以存储和操作少量员工信息的类。这些文件使用非异步模型,但可以以类似的方式使用异步类。

employee 类看起来像这样

  public class <code>Employee</code>
  {
    //The Id property is marked as the Primary Key
    [SQLite.PrimaryKey, SQLite.AutoIncrement]
    //Key value
    public int Id { get; set; }

    public string LastName
    {
      get; set;
    }
    
    public string FirstName
    {
      get; set;
    }

    public DateTime DOB
    {
      get;set;
    }
  }

使用 SQLiteConnection 构造函数创建与数据库的连接,并将数据库表的路径作为参数。

    public static string DB_PATH = 
      Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, 
                   "SQLiteTest.sqlite"));

    /// <summary>
    /// Initialize the connection.
    /// </summary>
    /// <param name="path">The optional path. </param>
    /// <returns>True on success, false otherwise.</returns>
    public bool Initialize(string path = null)
    {
      bool retVal = false;
      this.dbPath = path ?? DB_PATH;
      if (this.dbPath != null)
      {
        dbConn = new SQLiteConnection(dbPath);
        retVal = (DbConn != null);
        if (retVal)
        {
          retVal = DbConn.CreateTable<Employee>() >= 0;
        }
      }
      return retVal;
    }

您可以使用该接口来 选择更新添加删除 记录。

    /// <summary>
    /// Retrieve all employees. 
    /// </summary>
    /// <returns>The collection of employees.</returns>
    public ObservableCollection<Employee> RetrieveEmployees()
    {
      List<Employee> audioList = DbConn.Table<Employee>().ToList<Employee>();
      ObservableCollection<Employee> EmployeeList = 
                           new ObservableCollection<Employee>(audioList);
      return EmployeeList;
    }

    /// <summary>
    /// Update an existing employee.
    /// </summary>
    /// <param name="newRecord">The record to update, with:
    /// 1.  The id of the record to update.
    /// 2.  The new values.  </param>
    public void UpdateEmployee(Employee newRecord)
    {
      var existingAudioNote = DbConn.Query<Employee>
          ("select * from Employee where Id =" + newRecord.Id).FirstOrDefault();
      if (existingAudioNote != null)
      {
        existingAudioNote.LastName = newRecord.LastName;
        existingAudioNote.FirstName = newRecord.FirstName;
        existingAudioNote.DOB = newRecord.DOB;
        DbConn.RunInTransaction(() =>
        {
          DbConn.Update(existingAudioNote);
        });
      }
    }

    /// <summary>
    /// Insert a new employee record.  The ID field
    /// is ignored. 
    /// </summary>
    /// <param name="newEmployee">The new employee record.</param>
    public void Insert(Employee newEmployee)
    {
      DbConn.RunInTransaction(() =>
              {
                DbConn.Insert(newEmployee);
              });
    }

    /// <summary>
    /// Delete a specific employee.
    /// </summary>
    /// <param name="Id">The id of the employee to delete.</param>
    public void Delete(int Id)
    {
      var existingEmployee = DbConn.Query<Employee>
          ("select * from Employee where Id =" + Id).FirstOrDefault();
      if (existingEmployee != null)
      {
        DbConn.RunInTransaction(() =>
        {
          DbConn.Delete(existingEmployee);
        });
      }
    }

最后,您可以在使用完接口后“清理”。

    /// <summary>
    /// Dispose the class. 
    /// </summary>
    public void Dispose()
    {
      if (DbConn != null)
      {
        dbConn.Close();
        dbConn.Dispose();
        dbConn = null;
      }
    }

使用可视化浏览器浏览数据库

可以从 http://sqlitebrowser.org 下载 Sqlite 的可视化浏览器。这对于开发中的数据库的测试和验证都很有用。

结论

本文介绍了如何开始使用 Sqlite。Sqlite 可以处理比此处显示的更复杂的操作,包括提交、回滚和多表操作。有关更多详细信息,请参阅下面的参考资料。

历史

  • 2018 年 8 月 21 日:初始版本
© . All rights reserved.