푸터 콘텐츠로 바로가기
.NET 도움말

Sqlite C# .NET (How It Works For Developers)

SQLite is a popular, lightweight, and self-contained relational database engine that is widely used in various data access applications and environment platforms. In the context of .NET development, SQLite source code serves as an excellent choice for integrating a reliable database solution control into your system applications. This article will delve into the world of SQLite transactions, exploring its features, advantages, and how to use it in your .NET projects effectively.

How to Use SQLite in C#

  1. Download SQLite library
  2. Create a database and insert the data
  3. Read using reader
  4. Use SQLite using Entity Framework and LINQ query method
  5. Generate PDF Report using IronPDF

What is SQLite?

SQLite is a popular open-source database engine that can be embedded in applications without requiring a separate server component. It is fast, reliable, and cross-platform. SQLite can be used with .NET project applications through various libraries that provide ADO.NET interfaces. One of these libraries is Microsoft.Data.SQLite. This allows you to use SQLite as a data source for your .NET applications, whether they are Console, Desktop, Web, or Mobile. You can also use Entity Framework Core to perform object-relational mapping and query your SQLite database using LINQ.

This article shows you how to use Microsoft.Data.Sqlite to develop, connect, and manipulate an SQLite database in a .NET Console Application. You will learn how to:

  • Install the Microsoft.Data.Sqlite NuGet package
  • Create a SQLite connection and execute SQL commands
  • Create and populate tables using data readers and parameters
  • Query data using data readers
  • Implement EntityFramework Core
  • Query data using LINQ
  • Generate PDF Report

Installing the SQLite Library

To use Microsoft.Data.Sqlite, you need to install the NuGet package that contains the library and its dependencies. You can do this using the Visual Studio Package Manager, the .NET Core CLI, or any other tool that supports NuGet. This article will use the Package Manager to create a Console Application and install Microsoft.Data.Sqlite. To do this, open a Package Manager Console and run the following commands:

Install-Package Microsoft.Data.Sqlite

The above command will install the package as shown below.

Creating SQLite Database

To work with a SQLite database, you need to create a SqliteConnection object that represents the connection to the database file. You can specify the file name and other options in the connection string. If the file does not exist, it will be created automatically. For example, the below program creates a connection to a database file named employee.db in the current directory:

using (var connection = new SqliteConnection("Data Source=employee.db"))
{
    connection.Open();
    // ...
}
using (var connection = new SqliteConnection("Data Source=employee.db"))
{
    connection.Open();
    // ...
}
$vbLabelText   $csharpLabel

The using statement ensures that the connection is closed and disposed of when it goes out of scope. To execute SQL commands, you need to create a SqlCommand object and associate it with the connection. You can set the CommandText property to the SQL statement you want to execute, and optionally add parameters to the Parameters collection. You can then call one of the methods of the SqlCommand object to execute the command, such as ExecuteNonQuery, ExecuteScalar, or ExecuteReader.

Create Table in SQLite

The following code creates a table named Employee using the ExecuteNonQuery method:

using (var connection = new SqliteConnection("Data Source=employee.db"))
{
    connection.Open();
    var command = connection.CreateCommand();
    command.CommandText = @"CREATE TABLE Employee (
        Id INTEGER PRIMARY KEY,
        FirstName TEXT NOT NULL,
        LastName TEXT NOT NULL,
        Designation TEXT NOT NULL )";
    command.ExecuteNonQuery();
}
using (var connection = new SqliteConnection("Data Source=employee.db"))
{
    connection.Open();
    var command = connection.CreateCommand();
    command.CommandText = @"CREATE TABLE Employee (
        Id INTEGER PRIMARY KEY,
        FirstName TEXT NOT NULL,
        LastName TEXT NOT NULL,
        Designation TEXT NOT NULL )";
    command.ExecuteNonQuery();
}
$vbLabelText   $csharpLabel

Insert Data into Table

To insert data into a table, you can use the same SqlCommand object and set the CommandText property to an INSERT statement. For example, the following code inserts three rows into the Employee table.

using (var connection = new SqliteConnection("Data Source=employee.db"))
{
    var command = connection.CreateCommand();
    StringBuilder builder = new StringBuilder();
    builder.Append("INSERT INTO Employee VALUES(1, 'John', 'Sami', 'CEO');");
    builder.Append("INSERT INTO Employee VALUES(2, 'David', 'Watson', 'Software Engineer');");
    builder.Append("INSERT INTO Employee VALUES(3, 'Victor', 'Khan', 'Content Writer');");
    connection.Open();
    command.CommandText = builder.ToString();
    command.ExecuteNonQuery();
}
using (var connection = new SqliteConnection("Data Source=employee.db"))
{
    var command = connection.CreateCommand();
    StringBuilder builder = new StringBuilder();
    builder.Append("INSERT INTO Employee VALUES(1, 'John', 'Sami', 'CEO');");
    builder.Append("INSERT INTO Employee VALUES(2, 'David', 'Watson', 'Software Engineer');");
    builder.Append("INSERT INTO Employee VALUES(3, 'Victor', 'Khan', 'Content Writer');");
    connection.Open();
    command.CommandText = builder.ToString();
    command.ExecuteNonQuery();
}
$vbLabelText   $csharpLabel

Read Data from SQLite

To read data from a table, you can use the ExecuteReader method of the SqlCommand object and set the CommandText property to a SELECT statement. This will return a SqliteDataReader object that allows you to iterate over the rows and access the values by column name or index. You can use the Read method to move to the next row, and the GetXXX methods to get the values as the appropriate data type. For example, the following code reads all the rows from the Employee table and prints them to the console:

using (var connection = new SqliteConnection("Data Source=employee.db"))
{
    var command = connection.CreateCommand();
    command.CommandText = @"SELECT * FROM Employee";
    connection.Open();
    using (var reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            var id = reader.GetInt32(0);
            string firstName = reader.GetString(1);
            string lastName = reader.GetString(2);
            string designation = reader.GetString(3);
            Console.WriteLine($"{id}: {firstName} - {lastName} - {designation}");
        }
    }
}
using (var connection = new SqliteConnection("Data Source=employee.db"))
{
    var command = connection.CreateCommand();
    command.CommandText = @"SELECT * FROM Employee";
    connection.Open();
    using (var reader = command.ExecuteReader())
    {
        while (reader.Read())
        {
            var id = reader.GetInt32(0);
            string firstName = reader.GetString(1);
            string lastName = reader.GetString(2);
            string designation = reader.GetString(3);
            Console.WriteLine($"{id}: {firstName} - {lastName} - {designation}");
        }
    }
}
$vbLabelText   $csharpLabel

Output

The output of this code is:

Sqlite C# .NET (How It Works For Developer): Figure 1 - Output

Querying Data

If you prefer to use LINQ to query your SQLite database, you can use Entity Framework Core to map your tables to classes and perform queries using LINQ expressions. To do this, you need to install the Microsoft.EntityFrameworkCore.Sqlite package, which depends on Microsoft.Data.Sqlite package. You also need to create a class that inherits from DbContext and represents the database context. This class must have a constructor that accepts a DbContextOptions parameter and passes it to the base constructor. It must also have a DbSet property for each table you want to map to a class. For example, the following code defines a Stock class and a DatabaseContext class:

using Microsoft.EntityFrameworkCore;
public class Stock
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string Symbol { get; set; } = string.Empty;
    public double Price { get; set; }
}
public class DatabaseContext : DbContext
{
    public DatabaseContext(DbContextOptions options) : base(options) { }
    public DbSet<Stock> Stock { get; set; }
}
using Microsoft.EntityFrameworkCore;
public class Stock
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;
    public string Symbol { get; set; } = string.Empty;
    public double Price { get; set; }
}
public class DatabaseContext : DbContext
{
    public DatabaseContext(DbContextOptions options) : base(options) { }
    public DbSet<Stock> Stock { get; set; }
}
$vbLabelText   $csharpLabel

To create the database context, you need to use the DbContextOptionsBuilder class and specify the connection string and the database provider. You can also use the Database.EnsureCreated method to create the database and the tables if they do not exist. For example, the following code creates the database context and the database:

var optionsBuilder = new DbContextOptionsBuilder<DatabaseContext>();
optionsBuilder.UseSqlite("Data Source=stock.db");
using (var context = new DatabaseContext(optionsBuilder.Options))
{
    context.Database.EnsureCreated();
}
var optionsBuilder = new DbContextOptionsBuilder<DatabaseContext>();
optionsBuilder.UseSqlite("Data Source=stock.db");
using (var context = new DatabaseContext(optionsBuilder.Options))
{
    context.Database.EnsureCreated();
}
$vbLabelText   $csharpLabel

To insert data into the database, you can use the Add or AddRange methods of the DbSet property and pass the objects you want to insert. You can also use the SaveChanges method to commit the changes to the database. For example, the following code inserts three Stocks into the database:

static void Main(string[] args)
{
    var optionsBuilder = new DbContextOptionsBuilder<DatabaseContext>();
    optionsBuilder.UseSqlite("Data Source=stock.db");
    using (var context = new DatabaseContext(optionsBuilder.Options))
    {
        context.Database.EnsureCreated();
        var stock = new List<Stock> {
            new Stock { Id = 1, Name = "NCR", Symbol = "$$", Price = 5.6 },
            new Stock { Id = 2, Name = "Google", Symbol = "GG", Price = 10.6 },
            new Stock { Id = 3, Name = "Apple", Symbol = "AA", Price = 3.6 }
        };
        context.AddRange(stock);
        context.SaveChanges();
    }
}
static void Main(string[] args)
{
    var optionsBuilder = new DbContextOptionsBuilder<DatabaseContext>();
    optionsBuilder.UseSqlite("Data Source=stock.db");
    using (var context = new DatabaseContext(optionsBuilder.Options))
    {
        context.Database.EnsureCreated();
        var stock = new List<Stock> {
            new Stock { Id = 1, Name = "NCR", Symbol = "$$", Price = 5.6 },
            new Stock { Id = 2, Name = "Google", Symbol = "GG", Price = 10.6 },
            new Stock { Id = 3, Name = "Apple", Symbol = "AA", Price = 3.6 }
        };
        context.AddRange(stock);
        context.SaveChanges();
    }
}
$vbLabelText   $csharpLabel

To query data, you can use the LINQ methods or expressions on the DbSet property and apply filters, projections, aggregations, and other operations. The queries will be translated to SQL statements and executed on the database. For example, the following code queries the stocks whose price is less than six dollars and prints their names:

using (var context = new DatabaseContext(optionsBuilder.Options))
{
    var cheapStocks = context.Stock.Where(p => p.Price < 6).Select(p => p.Name);
    Console.WriteLine("Stock Less than $6 are:");
    foreach (string stock in cheapStocks)
    {
        Console.WriteLine(stock);
    }
}
using (var context = new DatabaseContext(optionsBuilder.Options))
{
    var cheapStocks = context.Stock.Where(p => p.Price < 6).Select(p => p.Name);
    Console.WriteLine("Stock Less than $6 are:");
    foreach (string stock in cheapStocks)
    {
        Console.WriteLine(stock);
    }
}
$vbLabelText   $csharpLabel

Let's suppose we have a scenario where we need to create a PDF file containing the list of Stocks. We can easily do that by using IronPDF.

Introducing IronPDF

IronPDF is a library that helps you create, edit, and read PDF files in your .NET applications without the need for multiple packages. It can generate PDFs from HTML, URL, JavaScript, CSS, and many image formats, as well as add headers, footers, signatures, attachments, and passwords. It also supports cross-platform compatibility, multithreading, and async support.

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");
    }
}
$vbLabelText   $csharpLabel

Install IronPDF

To install the IronPDF in our project, write the following command in the Package Manager Console.

Install-Package IronPdf

This command will install IronPDF along with all its dependencies.

Add License Key

IronPDF requires a License Key to use it. We can easily get a trial license key from IronPDF Trial License Page.

Add this code to the startup of your application before IronPDF is used. This approach is universally effective and straightforward, working for both .NET Core and .NET Framework applications.

IronPdf.License.LicenseKey = "IRONSUITE.ABC.XYZ.MYCOMPANY.COM.ABC-DEPLOYMENT.TRIAL-P45MXL.TRIAL.EXPIRES.31.JAN.2028";
IronPdf.License.LicenseKey = "IRONSUITE.ABC.XYZ.MYCOMPANY.COM.ABC-DEPLOYMENT.TRIAL-P45MXL.TRIAL.EXPIRES.31.JAN.2028";
$vbLabelText   $csharpLabel

Create PDF File Containing Stock List

This C# code generates a PDF report from stock data stored in a SQLite database. It dynamically creates an HTML table, populates it with stock information, and uses a Chrome-based PDF renderer to convert the table into a downloadable "stock.pdf" file, facilitating efficient reporting and distribution of stock details.

var optionsBuilder = new DbContextOptionsBuilder<DatabaseContext>();
optionsBuilder.UseSqlite("Data Source=stock.db");
StringBuilder builder = new StringBuilder();
string style = "<!DOCTYPE html>\r\n<html>\r\n<head>\r\n<style>\r\n#stock {\r\n  font-family: Arial, Helvetica, sans-serif;\r\n  border-collapse: collapse;\r\n  width: 100%;\r\n}\r\n\r\n#stock td, #stock th {\r\n  border: 1px solid #ddd;\r\n  padding: 8px;\r\n}\r\n\r\n#stock tr:nth-child(even){background-color: #f2f2f2;}\r\n\r\n#stock tr:hover {background-color: #ddd;}\r\n\r\n#stock th {\r\n  padding-top: 12px;\r\n  padding-bottom: 12px;\r\n  text-align: left;\r\n  background-color: #04AA6D;\r\n  color: white;\r\n}\r\n</style>\r\n</head>\r\n<body>\r\n\r\n<h1>A Stock Table</h1>";
builder.Append(style);
builder.Append("<table id=\"stock\"><tr><td>Stock Symbol</td><td>Stock Name</td><td>Stock Price</td></tr>");
using (var context = new DatabaseContext(optionsBuilder.Options))
{
    var stocks = context.Stock;
    foreach (Stock stock in stocks)
    {
        builder.Append($"<tr><td>{stock.Symbol}</td><td>{stock.Name}</td><td>{stock.Price}</td></tr>");
    }
}
builder.Append("</table></body></html>");
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(builder.ToString());
pdf.SaveAs("stock.pdf");
var optionsBuilder = new DbContextOptionsBuilder<DatabaseContext>();
optionsBuilder.UseSqlite("Data Source=stock.db");
StringBuilder builder = new StringBuilder();
string style = "<!DOCTYPE html>\r\n<html>\r\n<head>\r\n<style>\r\n#stock {\r\n  font-family: Arial, Helvetica, sans-serif;\r\n  border-collapse: collapse;\r\n  width: 100%;\r\n}\r\n\r\n#stock td, #stock th {\r\n  border: 1px solid #ddd;\r\n  padding: 8px;\r\n}\r\n\r\n#stock tr:nth-child(even){background-color: #f2f2f2;}\r\n\r\n#stock tr:hover {background-color: #ddd;}\r\n\r\n#stock th {\r\n  padding-top: 12px;\r\n  padding-bottom: 12px;\r\n  text-align: left;\r\n  background-color: #04AA6D;\r\n  color: white;\r\n}\r\n</style>\r\n</head>\r\n<body>\r\n\r\n<h1>A Stock Table</h1>";
builder.Append(style);
builder.Append("<table id=\"stock\"><tr><td>Stock Symbol</td><td>Stock Name</td><td>Stock Price</td></tr>");
using (var context = new DatabaseContext(optionsBuilder.Options))
{
    var stocks = context.Stock;
    foreach (Stock stock in stocks)
    {
        builder.Append($"<tr><td>{stock.Symbol}</td><td>{stock.Name}</td><td>{stock.Price}</td></tr>");
    }
}
builder.Append("</table></body></html>");
var renderer = new ChromePdfRenderer();
var pdf = renderer.RenderHtmlAsPdf(builder.ToString());
pdf.SaveAs("stock.pdf");
$vbLabelText   $csharpLabel

The above C# code snippet is designed to create an HTML table displaying stock information from a SQLite database and subsequently convert it into a PDF file. It uses the Entity Framework Core library to interact with the database. Initially, it configures a DbContextOptionsBuilder to use SQLite with a specific connection string. The code then constructs an HTML string with embedded CSS styles for the table's appearance, creates a table structure with headers, queries the SQLite database for stock information, populates the HTML table with the retrieved data, and finally, utilizes a Chrome-based PDF renderer to convert the HTML content into a PDF file named "stock.pdf." The resulting PDF will contain a table presenting stock symbols, names, and prices.

Output is as

Sqlite C# .NET (How It Works For Developer): Figure 2 - Stock Table Output

Conclusion

In conclusion, leveraging SQLite in .NET for database management offers a lightweight and versatile solution. This article explored the integration of SQLite into .NET applications, showcasing its key features and advantages. The provided code demonstrated practical steps for creating, connecting, and manipulating an SQLite database in a .NET console application. Additionally, it highlighted the use of Microsoft.Data.Sqlite and Entity Framework Core for efficient data handling. The incorporation of IronPDF illustrated how to seamlessly generate a PDF report from the SQLite database, enhancing the application's capabilities for reporting and data distribution.

IronPDF offers various licensing options, depending on the number of developers, locations, projects, and redistribution needs. The licenses are perpetual and include one year of free support and updates.

자주 묻는 질문

SQLite란 무엇이며 .NET 개발에 인기가 있는 이유는 무엇인가요?

SQLite는 속도, 안정성 및 크로스 플랫폼 기능으로 인해 .NET 개발에서 널리 사용되는 경량의 독립형 관계형 데이터베이스 엔진입니다. 별도의 서버 구성 요소 없이 애플리케이션에 임베드할 수 있습니다.

SQLite를 내 .NET 애플리케이션에 통합하려면 어떻게 해야 하나요?

Microsoft.Data.Sqlite NuGet 패키지를 설치하여 SQLite를 .NET 애플리케이션에 통합할 수 있습니다. 이 패키지는 콘솔, 데스크톱, 웹 또는 모바일 앱 내에서 SQLite 데이터베이스를 만들고, 연결하고, 조작할 수 있는 ADO.NET 인터페이스를 제공합니다.

C#에서 SQLite 데이터베이스를 만들고 연결하려면 어떻게 해야 하나요?

C#에서 SQLite 데이터베이스를 만들고 연결하려면 SqliteConnection 클래스를 사용하여 연결을 설정합니다. 그런 다음 SQL 명령을 실행하여 테이블을 만들고 SqlCommand 개체를 사용하여 데이터를 조작할 수 있습니다.

.NET에서 SQLite와 함께 LINQ 쿼리를 사용할 수 있나요?

예, 엔티티 프레임워크 코어를 활용하여 .NET에서 SQLite와 함께 LINQ 쿼리를 사용할 수 있습니다. 이를 통해 객체 관계형 매핑이 가능하므로 DbContext 클래스 내의 DbSet 속성에 대해 LINQ 쿼리를 수행할 수 있습니다.

SQLite 데이터베이스 데이터에서 PDF 보고서를 생성하려면 어떻게 해야 하나요?

IronPDF를 사용하여 SQLite 데이터베이스 데이터에서 PDF 보고서를 생성할 수 있습니다. 데이터의 HTML 표현을 변환하거나 데이터베이스 콘텐츠를 직접 사용하여 자세한 PDF 보고서를 만들고 IronPDF의 렌더링 기능을 사용하여 내보낼 수 있습니다.

.NET 애플리케이션의 일반적인 SQLite 문제를 해결하려면 어떻게 해야 하나요?

.NET 애플리케이션의 일반적인 SQLite 문제는 Microsoft.Data.Sqlite 패키지가 올바르게 설치되었는지 확인하고, SQL 구문을 확인하고, 연결 문자열을 확인하여 해결할 수 있습니다. 디버깅 도구와 로그도 오류를 식별하고 해결하는 데 도움이 될 수 있습니다.

.NET 프로젝트에서 PDF 라이브러리를 설치하고 사용하려면 어떻게 해야 하나요?

.NET 프로젝트에 IronPDF와 같은 PDF 라이브러리를 설치하려면 패키지 관리자 콘솔에서 Install-Package IronPdf를 실행하세요. IronPDF가 설치되면 광범위한 API를 활용하여 PDF 파일을 생성, 편집 및 읽을 수 있습니다.

.NET과 함께 SQLite를 사용하면 어떤 이점이 있나요?

.NET과 함께 SQLite를 사용하면 단순성, 별도의 서버 필요 없음, 크로스 플랫폼 지원, 안정적인 성능 등의 이점을 얻을 수 있습니다. 경량 애플리케이션에 이상적이며 Microsoft.Data.Sqlite와 같은 라이브러리를 사용하여 쉽게 통합할 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.