8

I would like to read the table and column information in C#.NET Windows application. I know that there is SMO base access for SQL Server. On similar ground is there any API for SQLite?

wannabeLearner
  • 199
  • 1
  • 2
  • 16
Omkar
  • 2,129
  • 8
  • 33
  • 59

1 Answers1

17

You can use the GetSchema method :

DbProviderFactory factory = DbProviderFactories.GetFactory("System.Data.SQLite");
using (DbConnection connection = factory.CreateConnection())
{
    connection.ConnectionString = @"Data Source=D:\tmp\test.db";
    connection.Open();
    DataTable tables = connection.GetSchema("Tables");
    DataTable columns = connection.GetSchema("Columns");
    tables.Dump();
    columns.Dump();
}

GetSchema returns a DataTable that contains information about the tables, columns, or whatever you specify. Valid GetSchema arguments for SQLite include:

  • MetaDataCollections
  • DataSourceInformation
  • DataTypes
  • ReservedWords
  • Catalogs
  • Columns
  • Indexes
  • IndexColumns
  • Tables
  • Views
  • ViewColumns
  • ForeignKeys
  • Triggers
Thomas Levesque
  • 286,951
  • 70
  • 623
  • 758
  • 3
    According to [this stackoverflow post][1], the getSchema does not work for SQLite. I had the same problem and am now using "SQLiteCommand("PRAGMA table_info('tracks')", DB)" [1]: http://stackoverflow.com/questions/3268986/getting-table-schema-doesnt-seem-to-work-with-system-data-sqlite – e-motiv Jul 15 '13 at 11:18
  • @R-U-Bn, I just tried again, it works fine (at least with the official System.Data.SQLite provider) – Thomas Levesque Jul 15 '13 at 12:22
  • 1
    Thx @Thomas but I guess it's specific to some (hard- or soft-) configuration some of us have. (Using provider version 1.0.65) And I also mentioned it as a backup/quick jump for future users with the same problem. (No discredit meant ;-) ) – e-motiv Jul 17 '13 at 14:20
  • @ThomasLevesque how do I figure out what columns are in `DataTable tables = connection.GetSchema("Tables");` ? – Bruno Bieri Nov 30 '17 at 15:24
  • 1
    @BrunoBieri just enumerate `tables.Columns` ;) – Thomas Levesque Dec 03 '17 at 19:53
  • I just tried this on the most recent nuget package and got 'Specified method is not supported.' – Jeremy Holovacs Apr 27 '18 at 14:37