Usman Aziz
Posted on November 10, 2019
The database is considered to be an integral part of most of the applications. Be it a desktop, web or mobile application, database plays a vital role in storing, accessing and manipulating the data. There are many database management systems that allow creating and managing databases for you.
However, there could be a scenario when you need a way to extract data from database files, i.e. .db file, without installing a database management system or writing the SQL queries. How would you parse the database file in such a case and get the data from it?
In this article, I am going to demonstrate how easily you can extract the data from the tables in an SQLite database without writing SQL queries. I am going to use GroupDocs.Parser for .NET API which supports extracting data from databases via ADO.NET.
Steps to Extract Data from Tables in SQLite Database (.db)
1. Create a new project in Visual Studio.
2. Install GroupDocs.Parser for .NET from NuGet.
3. Add the following namespaces.
using System;
using System.Collections.Generic;
using System.IO;
using GroupDocs.Parser.Data;
using GroupDocs.Parser.Options;
4. Prepare the connection string.
string connectionString = string.Format("Provider=System.Data.Sqlite;Data Source={0};Version=3;", "sqlite.db");
5. Load the database file in the Parser object.
using (Parser parser = new Parser(connectionString, new LoadOptions(FileFormat.Database)))
{
// your code goes here
}
6. Get list of the tables in the database using Parser.GetToc method.
// Get a list of tables
IEnumerable<TocItem> toc = parser.GetToc();
7. Iterate over the tables and extract data.
// Iterate over tables
foreach (TocItem i in toc)
{
// Print the table name
Console.WriteLine(i.Text);
// Extract a table content as a text
using (TextReader reader = parser.GetText(i.PageIndex.Value))
{
Console.WriteLine(reader.ReadToEnd());
}
}
Complete Code
string connectionString = string.Format("Provider=System.Data.Sqlite;Data Source={0};Version=3;", "sqlite.db");
// Create an instance of Parser class to extract tables from the database.
// Connection string is passed as first parameter and LoadOptions is set to Database file format.
using (Parser parser = new Parser(connectionString, new LoadOptions(FileFormat.Database)))
{
// Get a list of tables
IEnumerable<TocItem> toc = parser.GetToc();
// Iterate over tables
foreach (TocItem i in toc)
{
// Print the table name
Console.WriteLine(i.Text);
// Extract a table content as a text
using (TextReader reader = parser.GetText(i.PageIndex.Value))
{
Console.WriteLine(reader.ReadToEnd());
}
}
}
Output
Cheers!
Posted on November 10, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.