c# - 如何使用 SQLite.NET 从现有的 sqlite 数据库中获取表名列表?

标签 c# sqlite

使用 sqlite.net nuget package ,如何使用 SQLiteConnection 实例从数据库中获取表列表?我需要此功能,以便我可以检测到我的数据库架构何时发生更改以及数据库何时需要重建。

例如,我定义了实体:

public class Body
{
    [PrimaryKey]
    public int PrimaryKey { get; set; }
}

public class Foot
{
    [PrimaryKey]
    public int PrimaryKey { get; set; }
}

public class Leg
{
    [PrimaryKey]
    public int PrimaryKey { get; set; }

}

我需要检索包含以下内容的字符串列表中的表:Body、Leg、Foot

SQLiteConnection 类具有可以执行此行为的 TableMappings 属性。只有调用SQLiteConnection.CreateTable后才能使用;这是不正确的,因为调用 CreateTable 会为对象生成表绑定(bind)并执行 create table if not exists 命令,从而更改架构。

查询 "SELECT NAME from sqlite_master" 可以执行此操作(我已经在数据库浏览器中对其进行了测试)但我无法使用 Execute 执行它,ExecuteScalarQuery。如何使用此命令检索数据库中的表列表?

最佳答案

以下扩展方法提供了在不使用 ORM 层的情况下查询现有数据库中的表的能力:

using System;
using System.Collections.Generic;
using SQLite;

namespace MyApplication
{
    public static class SqliteExtensions
    {
        public static List<string> Tables (this SQLiteConnection connection)
        {
            const string GET_TABLES_QUERY = "SELECT NAME from sqlite_master";

            List<string> tables = new List<string> ();

            var statement = SQLite3.Prepare2 (connection.Handle, GET_TABLES_QUERY);

            try {
                bool done = false;
                while (!done) {
                    SQLite3.Result result = SQLite3.Step (statement);

                    if (result == SQLite3.Result.Row) {

                        var tableName = SQLite3.ColumnString (statement, 0);

                        tables.Add(tableName);
                    } else if (result == SQLite3.Result.Done) {
                        done = true;
                    } else {
                        throw SQLiteException.New (result, SQLite3.GetErrmsg (connection.Handle));
                    }
                }
            }
            finally {   
                SQLite3.Finalize (statement);
            }

            return tables;
        }
    }
}

关于c# - 如何使用 SQLite.NET 从现有的 sqlite 数据库中获取表名列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32833359/

相关文章:

ios - 在两台 iPhone 之间同步 SQLite 数据库

datetime - SQLite3 创建索引时分割日期

android - 插入的行 ID 大于表中的所有条目

c# - WPF:如何同时处理不同的屏幕分辨率“DPI”?

c# - Umbraco - 如何在代码中访问内容蓝图(模板)

c# - 如何从 App.config 中读取这个自定义配置?

c# - 在 GridView 中对 DropDownList 选定值使用 Eval

c# - NHibernate Cascade=保存更新”?

ios - 从另一个 View Controller 访问数据库函数时出现 Swift 4 SQLite 问题

android - SQLITE 批量插入以通过 UPDATE 和 INSERT 增加优化