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