[英]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"
可以做到这一点(我已经在数据库浏览器中对其进行了测试),但是无法使用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;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.