[英]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.