.NET HELP

C# SQLite (How it Works For Developers)

Published November 14, 2023
Share:

Introduction to SQLite

SQLite is a self-contained, serverless, and zero-configuration database engine used in various applications, including desktop, web, and mobile applications. In this tutorial, we will dive into using SQLite with C#. Using simple and easily understandable examples, you'll learn how to create, manage, and interact with an SQLite database.

What is SQLite?

SQLite is a lightweight and efficient database that stores data in a single file. Unlike traditional databases, it doesn't require a separate server. This makes it a great choice for applications that need a database without the complexity of a full-fledged database system.

Setting Up SQLite in a C#

Using NuGet Package Manager

To work with SQLite in a C# project, you'll need to install the necessary SQLite library. This can be done through the NuGet Package Manager.

  1. Open Visual Studio and create a new Console Application.
  2. Right-click on the project and select "Manage NuGet Packages."
  3. Search for "SQLite" and install the package.

Establishing a Connection

Connection String

A connection string is a string that specifies information about a data source and the means of connecting to it. In SQLite, the connection string will often look like this:

string connectionString = "Data Source=mydatabase.db;";
string connectionString = "Data Source=mydatabase.db;";
Dim connectionString As String = "Data Source=mydatabase.db;"
VB   C#

Connection Object

You can create a connection object using the new SQLiteConnection data source.

using SQLite;
var connection = new SQLiteConnection(connectionString);
using SQLite;
var connection = new SQLiteConnection(connectionString);
Imports SQLite
Private connection = New SQLiteConnection(connectionString)
VB   C#

Creating a Table

Create Table

Creating a table is fundamental when working with any database. Here's how you create a table using SQLite code.

string query = "CREATE TABLE person (id INTEGER PRIMARY KEY, name TEXT)";
var command = new SQLiteCommand(query, connection);
command.ExecuteNonQuery();
string query = "CREATE TABLE person (id INTEGER PRIMARY KEY, name TEXT)";
var command = new SQLiteCommand(query, connection);
command.ExecuteNonQuery();
Dim query As String = "CREATE TABLE person (id INTEGER PRIMARY KEY, name TEXT)"
Dim command = New SQLiteCommand(query, connection)
command.ExecuteNonQuery()
VB   C#
  • Id Integer Primary Key: Sets the 'id' column as the primary key.
  • Table Name: The name you want to give your database table.

Inserting Data

Insert Rows

To insert data into a table, you'll need to use an INSERT command.

string query = "INSERT INTO person (name) VALUES ('John')";
var command = new SQLiteCommand(query, connection);
command.ExecuteNonQuery();
string query = "INSERT INTO person (name) VALUES ('John')";
var command = new SQLiteCommand(query, connection);
command.ExecuteNonQuery();
Dim query As String = "INSERT INTO person (name) VALUES ('John')"
Dim command = New SQLiteCommand(query, connection)
command.ExecuteNonQuery()
VB   C#

Parameterized Command

Parameterized commands can protect your application from SQL Injection attacks. This approach uses parameters instead of inserting values directly into the query.

string query = "INSERT INTO person (name) VALUES (@name)";
var command = new SQLiteCommand(query, connection);
command.Parameters.AddWithValue("@name", "Iron Developer");
command.ExecuteNonQuery();
string query = "INSERT INTO person (name) VALUES (@name)";
var command = new SQLiteCommand(query, connection);
command.Parameters.AddWithValue("@name", "Iron Developer");
command.ExecuteNonQuery();
Dim query As String = "INSERT INTO person (name) VALUES (@name)"
Dim command = New SQLiteCommand(query, connection)
command.Parameters.AddWithValue("@name", "Iron Developer")
command.ExecuteNonQuery()
VB   C#

Retrieving Data

Select Statement

To retrieve data from the database table, use a SELECT statement.

string query = "SELECT * FROM person";
var command = new SQLiteCommand(query, connection);
var reader = command.ExecuteReader();
while (reader.Read())
{
    Console.WriteLine(reader ["name"]);
}
string query = "SELECT * FROM person";
var command = new SQLiteCommand(query, connection);
var reader = command.ExecuteReader();
while (reader.Read())
{
    Console.WriteLine(reader ["name"]);
}
Dim query As String = "SELECT * FROM person"
Dim command = New SQLiteCommand(query, connection)
Dim reader = command.ExecuteReader()
Do While reader.Read()
	Console.WriteLine(reader ("name"))
Loop
VB   C#

Advanced Features

SQLite Transactions

Transactions allow you to execute multiple operations in a single atomic action. Here's how to use transactions:

var transaction = connection.BeginTransaction();
try
{
    // Multiple insert, update, or delete operations
    transaction.Commit();
}
catch
{
    transaction.Rollback();
}
var transaction = connection.BeginTransaction();
try
{
    // Multiple insert, update, or delete operations
    transaction.Commit();
}
catch
{
    transaction.Rollback();
}
Dim transaction = connection.BeginTransaction()
Try
	' Multiple insert, update, or delete operations
	transaction.Commit()
Catch
	transaction.Rollback()
End Try
VB   C#

Object-Relational Mapping (ORM) with Entity Framework

Entity Framework (EF) is a widely used ORM tool within the .NET ecosystem. It simplifies database programming by allowing developers to work with relational data using domain-specific objects. Here's how you can use Entity Framework with SQLite.

1. Installing Entity Framework

First, make sure you have installed the Entity Framework NuGet package specific to SQLite:

  1. Open the NuGet Package Manager in Visual Studio.
  2. Search for "Entity Framework SQLite" and install it.

2. Creating Entity Classes

Entity classes are representations of database tables. You can create a class for each table with which you intend to interact.

public class Person
{
    public int Id { get; set; } // Primary Key
    public string Name { get; set; }
}
public class Person
{
    public int Id { get; set; } // Primary Key
    public string Name { get; set; }
}
Public Class Person
	Public Property Id() As Integer ' -  Primary Key
	Public Property Name() As String
End Class
VB   C#

3. DbContext

You'll need to create a class that inherits from DbContext. This class represents the session with the database and allows you to query and save instances of the entities.

public class MyDbContext : DbContext
{
    public DbSet<Person> Persons { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Data Source=mydatabase.db;");
    }
}
public class MyDbContext : DbContext
{
    public DbSet<Person> Persons { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        optionsBuilder.UseSqlite("Data Source=mydatabase.db;");
    }
}
Public Class MyDbContext
	Inherits DbContext

	Public Property Persons() As DbSet(Of Person)

	Protected Overrides Sub OnConfiguring(ByVal optionsBuilder As DbContextOptionsBuilder)
		optionsBuilder.UseSqlite("Data Source=mydatabase.db;")
	End Sub
End Class
VB   C#

4. CRUD Operations

Entity Framework simplifies Create, Read, Update, and Delete (CRUD) operations. Here's how you can insert a new record:

using (var db = new MyDbContext())
{
    db.Persons.Add(new Person { Name = "John" });
    db.SaveChanges();
}
using (var db = new MyDbContext())
{
    db.Persons.Add(new Person { Name = "John" });
    db.SaveChanges();
}
Using db = New MyDbContext()
	db.Persons.Add(New Person With {.Name = "John"})
	db.SaveChanges()
End Using
VB   C#

Reading, updating, and deleting records are similarly streamlined and straightforward with Entity Framework, allowing for concise and maintainable code.

Working with XML Files and Other Data Providers

SQLite is not limited to relational data; it also provides flexibility in handling other data types, including XML files.

1. Storing XML Data

You can store XML data within an SQLite database. This might be useful if you work with configuration data or other hierarchical structures.

string xmlData = "<person><name>John</name></person>";
string query = "INSERT INTO xmltable (data) VALUES (@data)";
var command = new SQLiteCommand(query, connection);
command.Parameters.AddWithValue("@data", xmlData);
command.ExecuteNonQuery();
string xmlData = "<person><name>John</name></person>";
string query = "INSERT INTO xmltable (data) VALUES (@data)";
var command = new SQLiteCommand(query, connection);
command.Parameters.AddWithValue("@data", xmlData);
command.ExecuteNonQuery();
Dim xmlData As String = "<person><name>John</name></person>"
Dim query As String = "INSERT INTO xmltable (data) VALUES (@data)"
Dim command = New SQLiteCommand(query, connection)
command.Parameters.AddWithValue("@data", xmlData)
command.ExecuteNonQuery()
VB   C#

Retrieving XML Data

You can retrieve and work with XML data using standard XML parsing techniques in C#.

string query = "SELECT data FROM xmltable WHERE id = 1";
var command = new SQLiteCommand(query, connection);
var reader = command.ExecuteReader();
string xmlData = reader ["data"].ToString();

// Parse the XML data as needed
string query = "SELECT data FROM xmltable WHERE id = 1";
var command = new SQLiteCommand(query, connection);
var reader = command.ExecuteReader();
string xmlData = reader ["data"].ToString();

// Parse the XML data as needed
Dim query As String = "SELECT data FROM xmltable WHERE id = 1"
Dim command = New SQLiteCommand(query, connection)
Dim reader = command.ExecuteReader()
Dim xmlData As String = reader ("data").ToString()

' Parse the XML data as needed
VB   C#

Working with Other Data Providers

SQLite also integrates well with various data providers, allowing for interoperability and flexibility. This means that you can seamlessly switch between different databases or even combine different data sources within a single application.

Introducing the Iron Suit A Powerful Set of Libraries

After exploring the realms of SQLite and logical operators in C#, it's time to introduce a remarkable collection of tools that complement and enhance the development experience in the .NET environment. The Iron Suit is a collection of powerful libraries comprising IronPDF, IronXL, IronOCR, and IronBarcode, each serving distinct purposes.

IronPDF: C# PDF Library

IronPDF is a comprehensive library designed to create, read, and manipulate PDF files in C#. Whether you need to generate reports, invoices, or any documents in PDF format, IronPDF has you covered. A unique feature of IronPDF is the ability to convert HTML to PDF. You can render HTML as a PDF document, including CSS, JavaScript, and images, making it a potent tool. Check out this tutorial on how to convert HTML to PDF for a step-by-step guide.

IronPDF's HTML to PDF feature is its main highlight, preserving all layouts and styles. It generates PDFs from web content, ideal for reports, invoices, and documentation. You can convert HTML files, URLs, and HTML strings to PDFs seamlessly.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
VB   C#

IronPDF can be an essential tool when working with SQLite databases. You can generate PDF reports from your SQLite database data, allowing for seamless data presentation and sharing.

IronXL: Excel File Management Made Easy

IronXL allows developers to read, write, and manipulate Excel files effortlessly. It's compatible with XLS, XLSX, and more, making it an ideal tool for handling spreadsheet data. You can read Excel files, manipulate them, and even create new files from scratch. IronXL's functionality integrates well with database management, including SQLite, for exporting and importing data.

IronOCR: Optical Character Recognition in C#

With IronOCR, scanning text from images and PDF files is a breeze. It's a versatile OCR (Optical Character Recognition) library that recognizes text from various sources.

Imagine storing scanned documents in an SQLite database and using IronOCR to retrieve and recognize the text within those documents. The possibilities are endless, providing powerful text retrieval and search functionality.

IronBarcode: The Ultimate Barcode Generation and Reading Library

Barcode generation and reading are made simple with IronBarcode. It supports multiple barcode formats and provides a robust API for all barcode-related needs. IronBarcode can play an essential role in applications using SQLite, where barcodes might represent products or other data entities. Storing and retrieving barcodes from the SQLite database enhances data integrity and facilitates quick access.

Conclusion

SQLite is a powerful yet lightweight database engine that's great for beginners and professionals alike. From creating tables and inserting rows to managing transactions and preventing SQL Injection attacks, SQLite offers many features. Whether you're building a console or mobile application or need to work with foreign keys and datasets, SQLite is an excellent choice.

The Iron Suit, comprising IronPDF, IronXL, IronOCR, and IronBarcode, is a treasure trove of tools that extend the capabilities of your C# development projects, whether you're working with SQLite databases or any other domains.

What's even more appealing is that each of these products offers a free trial, giving you ample time to explore and understand the vast array of functionalities they provide. Once you decide to continue with these tools, the licensing starts from $749 per product. You can also buy the complete Iron Suit bundle at the price of just two individual products.

< PREVIOUS
Signalr C# (How it Works For Developers)
NEXT >
C# Web App (How it Works For Developers)

Ready to get started? Version: 2024.10 just released

Free NuGet Download Total downloads: 11,308,499 View Licenses >