2015-09-28 59 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; 
     } 
    } 
} 
相关问题