繁体   English   中英

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

[英]How can I get a list of table names from an existing sqlite database using SQLite.NET?

使用sqlite.net nuget包 ,如何使用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为对象生成表绑定, create table if not exists执行create table if not exists命令,从而更改架构。

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM