Skip to main content
 首页 » 编程设计

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

2024年02月05日11开发

使用 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 执行它,ExecuteScalar 或 Query。如何使用此命令检索数据库中的表列表?

请您参考如下方法:

以下扩展方法提供了在不使用 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; 
        } 
    } 
}