2015-09-28 41 views
1

使用sqlite.net nuget package,我如何才能得到使用SQLiteConnection實例的數據庫表的列表?我需要這個功能,所以我可以檢測到我的數據庫架構發生了什麼變化,並且數據庫需要重建。如何使用SQLite.NET從現有的sqlite數據庫獲取表名列表?

例如,我定義的實體:

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,從而改變模式。

查詢"SELECT NAME from sqlite_master"可以做到這一點(我已經在數據庫瀏覽器中測試過),但使用ExecuteExecuteScalarQuery我不能執行它。如何使用此命令檢索數據庫中的表的列表?

+0

小的修正 - 當任何類型被傳遞到連接的TableMappings屬性被填充。所以調用connection.Get 將在TableMappings中添加一個T的條目。這只是一個緩存 - 有點誤導 – rikkit

回答

4

以下擴展方法提供了查詢現有的數據庫中的表,而無需使用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; 
     } 
    } 
} 
相關問題