C# SQLite(开发者如何使用)
SQLite 简介
SQLite 是一个自包含、无服务器、零配置的数据库引擎,广泛用于包括桌面、网页和移动应用程序在内的各种应用程序中。 在本教程中,我们将深入探讨如何在 C# 中使用 SQLite。 通过简单且易于理解的示例,您将学习如何创建、管理和与 SQLite 数据库交互。
什么是 SQLite?
SQLite 是一个轻量级且高效的数据库,将数据存储在一个文件中。与传统数据库不同,它不需要单独的服务器。 这使得它成为需要数据库但不需要完整数据库系统复杂性的应用程序的一个不错的选择。
在 C# 中设置 SQLite
使用 NuGet 包管理器
要在 C# 项目中使用 SQLite,您需要安装必要的 SQLite 库。 这可以通过 NuGet 包管理器完成。
- 打开 Visual Studio 并创建一个新的控制台应用程序。
- 右键单击项目并选择"管理 NuGet 包"。
- 搜索"SQLite"并安装该包。
建立连接
连接字符串
连接字符串是一个指定数据源信息和连接方式的字符串。 在 SQLite 中,连接字符串通常看起来像这样:
string connectionString = "Data Source=mydatabase.db;";string connectionString = "Data Source=mydatabase.db;";Dim connectionString As String = "Data Source=mydatabase.db;"连接对象
您可以使用 System.Data.SQLite 命名空间中的 SQLiteConnection 类创建连接对象。
using System.Data.SQLite;
// Initialize a connection to the SQLite database
var connection = new SQLiteConnection(connectionString);
// Open the connection
connection.Open();using System.Data.SQLite;
// Initialize a connection to the SQLite database
var connection = new SQLiteConnection(connectionString);
// Open the connection
connection.Open();Imports System.Data.SQLite
' Initialize a connection to the SQLite database
Private connection = New SQLiteConnection(connectionString)
' Open the connection
connection.Open()创建表
创建表
在使用任何数据库时,创建表是至关重要的。 以下是如何使用 SQLite 代码创建表的方法。
// SQL command to create a new table "person"
string query = "CREATE TABLE IF NOT EXISTS person (id INTEGER PRIMARY KEY, name TEXT)";
// Create a command object with the SQL query and connection
var command = new SQLiteCommand(query, connection);
// Execute the command to create the table
command.ExecuteNonQuery();// SQL command to create a new table "person"
string query = "CREATE TABLE IF NOT EXISTS person (id INTEGER PRIMARY KEY, name TEXT)";
// Create a command object with the SQL query and connection
var command = new SQLiteCommand(query, connection);
// Execute the command to create the table
command.ExecuteNonQuery();' SQL command to create a new table "person"
Dim query As String = "CREATE TABLE IF NOT EXISTS person (id INTEGER PRIMARY KEY, name TEXT)"
' Create a command object with the SQL query and connection
Dim command = New SQLiteCommand(query, connection)
' Execute the command to create the table
command.ExecuteNonQuery()- Id Integer Primary Key: 将 'id' 列设置为主键。
- 表名: 您想要为数据库表命名的名称。
插入数据
插入行
要向表中插入数据,您需要使用 INSERT 命令。
// SQL command to insert a new row into the "person" table
string query = "INSERT INTO person (name) VALUES ('John')";
var command = new SQLiteCommand(query, connection);
command.ExecuteNonQuery();// SQL command to insert a new row into the "person" table
string query = "INSERT INTO person (name) VALUES ('John')";
var command = new SQLiteCommand(query, connection);
command.ExecuteNonQuery();' SQL command to insert a new row into the "person" table
Dim query As String = "INSERT INTO person (name) VALUES ('John')"
Dim command = New SQLiteCommand(query, connection)
command.ExecuteNonQuery()参数化命令
参数化命令可以保护您的应用程序免受 SQL 注入攻击。 这种方法使用参数而不是直接在查询中插入值。
// SQL command with a parameter to insert data safely
string query = "INSERT INTO person (name) VALUES (@name)";
var command = new SQLiteCommand(query, connection);
command.Parameters.AddWithValue("@name", "Iron Developer");
command.ExecuteNonQuery();// SQL command with a parameter to insert data safely
string query = "INSERT INTO person (name) VALUES (@name)";
var command = new SQLiteCommand(query, connection);
command.Parameters.AddWithValue("@name", "Iron Developer");
command.ExecuteNonQuery();' SQL command with a parameter to insert data safely
Dim query As String = "INSERT INTO person (name) VALUES (@name)"
Dim command = New SQLiteCommand(query, connection)
command.Parameters.AddWithValue("@name", "Iron Developer")
command.ExecuteNonQuery()检索数据
选择语句
要从数据库表中检索数据,请使用 SELECT 语句。
// SQL command to select all rows from the "person" table
string query = "SELECT * FROM person";
var command = new SQLiteCommand(query, connection);
var reader = command.ExecuteReader();
// Loop through the result set and read data
while (reader.Read())
{
Console.WriteLine(reader["name"]);
}// SQL command to select all rows from the "person" table
string query = "SELECT * FROM person";
var command = new SQLiteCommand(query, connection);
var reader = command.ExecuteReader();
// Loop through the result set and read data
while (reader.Read())
{
Console.WriteLine(reader["name"]);
}' SQL command to select all rows from the "person" table
Dim query As String = "SELECT * FROM person"
Dim command = New SQLiteCommand(query, connection)
Dim reader = command.ExecuteReader()
' Loop through the result set and read data
Do While reader.Read()
Console.WriteLine(reader("name"))
Loop高级功能
SQLite 事务
事务允许您在单个原子操作中执行多个操作。 以下是如何使用事务的方法:
var transaction = connection.BeginTransaction();
try
{
// Example of multiple operations in a transaction
var insertCommand = new SQLiteCommand("INSERT INTO person (name) VALUES ('Alice')", connection, transaction);
insertCommand.ExecuteNonQuery();
var updateCommand = new SQLiteCommand("UPDATE person SET name = 'Bob' WHERE name = 'Alice'", connection, transaction);
updateCommand.ExecuteNonQuery();
transaction.Commit(); // Commit the transaction if all operations succeed
}
catch
{
transaction.Rollback(); // Rollback the transaction if any operation fails
}var transaction = connection.BeginTransaction();
try
{
// Example of multiple operations in a transaction
var insertCommand = new SQLiteCommand("INSERT INTO person (name) VALUES ('Alice')", connection, transaction);
insertCommand.ExecuteNonQuery();
var updateCommand = new SQLiteCommand("UPDATE person SET name = 'Bob' WHERE name = 'Alice'", connection, transaction);
updateCommand.ExecuteNonQuery();
transaction.Commit(); // Commit the transaction if all operations succeed
}
catch
{
transaction.Rollback(); // Rollback the transaction if any operation fails
}Dim transaction = connection.BeginTransaction()
Try
' Example of multiple operations in a transaction
Dim insertCommand = New SQLiteCommand("INSERT INTO person (name) VALUES ('Alice')", connection, transaction)
insertCommand.ExecuteNonQuery()
Dim updateCommand = New SQLiteCommand("UPDATE person SET name = 'Bob' WHERE name = 'Alice'", connection, transaction)
updateCommand.ExecuteNonQuery()
transaction.Commit() ' Commit the transaction if all operations succeed
Catch
transaction.Rollback() ' Rollback the transaction if any operation fails
End Try使用实体框架进行对象关系映射 (ORM)
Entity Framework (EF) 是 .NET 生态系统中广泛使用的 ORM 工具。 它通过允许开发人员使用特定领域的对象来处理关系数据,简化数据库编程。 以下是如何将 Entity Framework 与 SQLite 一起使用的方法。
1. 安装 Entity Framework
首先,确保您已经安装了针对 SQLite 的 Entity Framework NuGet 包:
- 在 Visual Studio 中打开 NuGet 包管理器。
- 搜索"Entity Framework SQLite"并安装它。
2. 创建实体类
实体类是数据库表的表示。 您可以为每个您打算交互的表创建一个类。
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 Class3. DbContext
您将需要创建一个继承自 DbContext 的类。 此类表示与数据库的会话,并允许您查询和保存实体的实例。
using Microsoft.EntityFrameworkCore;
public class MyDbContext : DbContext
{
public DbSet<Person> Persons { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=mydatabase.db;");
}
}using Microsoft.EntityFrameworkCore;
public class MyDbContext : DbContext
{
public DbSet<Person> Persons { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=mydatabase.db;");
}
}Imports Microsoft.EntityFrameworkCore
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 Class4. CRUD 操作
Entity Framework 简化了创建、读取、更新和删除(CRUD)操作。 以下是如何插入新记录:
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读取、更新和删除记录同样通过 Entity Framework 简化,使得代码简单易维护。
使用 XML 文件和其他数据提供程序
SQLite 不仅限于关系数据; 它还在处理其他数据类型方面提供灵活性,包括 XML 文件。
1. 存储 XML 数据
您可以在 SQLite 数据库中存储 XML 数据。 如果您处理配置数据或其他层次结构,这可能会很有用。
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()检索 XML 数据
您可以使用标准的 XML 解析技术在 C# 中检索和处理 XML 数据。
string query = "SELECT data FROM xmltable WHERE id = 1";
var command = new SQLiteCommand(query, connection);
var reader = command.ExecuteReader();
string xmlData;
// Read the XML data from the query result
if (reader.Read())
{
xmlData = reader["data"].ToString();
}
// Parse the XML data as needed using an XML parserstring query = "SELECT data FROM xmltable WHERE id = 1";
var command = new SQLiteCommand(query, connection);
var reader = command.ExecuteReader();
string xmlData;
// Read the XML data from the query result
if (reader.Read())
{
xmlData = reader["data"].ToString();
}
// Parse the XML data as needed using an XML parserDim query As String = "SELECT data FROM xmltable WHERE id = 1"
Dim command = New SQLiteCommand(query, connection)
Dim reader = command.ExecuteReader()
Dim xmlData As String
' Read the XML data from the query result
If reader.Read() Then
xmlData = reader("data").ToString()
End If
' Parse the XML data as needed using an XML parser使用其他数据提供程序
SQLite 还可以与各种数据提供程序很好地集成,实现兼容性和灵活性。 这意味着您可以在单个应用程序中无缝地在不同的数据库之间切换,甚至结合不同的数据源。
介绍 Iron Suite:强大的库套件
在探索了 SQLite 和 C# 中的逻辑操作符之后,是时候介绍一组杰出的工具了,这些工具可以在 .NET 环境中补充和增强开发体验。 Iron Suite 是一组强大的库,包括 IronPDF、IronXL、IronOCR 和 IronBarcode,每一个都有不同的用途。
IronPDF:C# PDF 库
IronPDF 综合指南 是一个设计用于创建、读取和操作 C# 中的 PDF 文件的综合库。 无论您是需要生成报告、发票,还是任何 PDF 格式的文件,IronPDF 都能满足您的需求。 IronPDF 的一个独特功能是能够将 HTML 转换为 PDF。 您可以将 HTML 渲染为 PDF 文档,包括 CSS、JavaScript 和图像,使其成为一个强大的工具。 查看关于 使用 IronPDF 将 HTML 转换为 PDF 的教程,了解分步指南。
IronPDF 的 HTML 到 PDF 功能 是其主要亮点,保留所有布局和样式。 它从网页内容生成 PDF,非常适合报告、发票和文档。 您可以无缝地将 HTML 文件、URL 和 HTML 字符串转换为 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");
}
}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在处理 SQLite 数据库时,IronPDF 可能是一个重要工具。 您可以从 SQLite 数据库数据中生成 PDF 报告,实现无缝的数据展示和共享。
IronXL:轻松实现 Excel 文件管理
探索 IronXL 的 Excel 集成,使开发人员可以轻松地读取、编写和操作 Excel 文件。 它兼容 XLS、XLSX 等格式,是处理电子表格数据的理想工具。 您可以读取 Excel 文件,操作它们,甚至从头开始创建新文件。 IronXL 的功能与数据库管理(包括 SQLite)很好地集成,用于导出和导入数据。
IronOCR:C# 中的光学字符识别
借助 IronOCR 进行文本识别,从图像和 PDF 文件中扫描文本变得非常简单。 这是一个多功能的 OCR(光学字符识别)库,可以识别来自各种来源的文本。
想象一下,将扫描的文档存储在 SQLite 数据库中,并使用 IronOCR 来检索和识别这些文档中的文本。 这种可能性是无限的,提供了强大的文本检索和搜索功能。
IronBarcode:终极条码生成和读取库
通过 IronBarcode 强大的条码集成,条码的生成和读取变得简单。 它支持多种条码格式,并为所有条码相关需求提供了一个强大的 API。 IronBarcode 可以在使用 SQLite 的应用程序中发挥重要作用,条码可能代表产品或其他数据实体。 从 SQLite 数据库中存储和检索条码,增强数据的完整性并促使快速访问。
结论
SQLite 是一个功能强大且轻量级的数据库引擎,非常适合初学者和专业人士。从创建表和插入行到管理事务和防止 SQL 注入攻击,SQLite 提供了许多功能。 无论您是构建控制台还是移动应用程序,或者需要处理外键和数据集,SQLite 都是一个不错的选择。
包含 IronPDF、IronXL、IronOCR 和 IronBarcode 的 Iron Suite 是一组工具的宝库,可以扩展您 C# 开发项目的能力,无论您是在与 SQLite 数据库一起工作还是在其他领域。
更加吸引人的是每个产品提供Iron Software 产品的免费试用版,让您有充足的时间来探索和理解它们所提供的大量功能。一旦您决定继续使用这些工具,许可证从每个产品的 Litelicense 开始。 您还可以以仅两个独立产品的价格购买完整的 Iron Suite 套装。
常见问题解答
如何在C#项目中使用NuGet设置SQLite?
要在C#项目中使用NuGet设置SQLite,打开Visual Studio并创建一个新的控制台应用程序。访问NuGet包管理器,搜索'SQLite'并安装该包。这将SQLite库集成到您的项目中进行数据库操作。
使用SQLite为C#应用程序带来哪些好处?
SQLite是一个轻量级的无服务器数据库引擎,将数据存储在一个文件中,使其成为需要简单高效数据库解决方案而无需传统数据库系统复杂性的应用程序的理想选择。
如何在C#中连接SQLite数据库?
您可以通过创建一个类似Data Source=mydatabase.db;的连接字符串以及使用System.Data.SQLite命名空间中的SQLiteConnection类来建立和打开连接。
如何在使用C#的SQLite数据库上进行CRUD操作?
使用SQL命令如INSERT,SELECT,UPDATE和DELETE,可以在C#中对SQLite数据库执行CRUD操作。这些命令可以通过SQLiteCommand对象执行。
事务在SQLite中起什么作用?
SQLite中的事务允许以单个原子操作执行多个操作。您可以使用connection.BeginTransaction()开始一个事务,执行必要的操作,然后根据结果提交或回滚事务。
如何在C#项目中使用SQLite的Entity Framework?
要使用Entity Framework与SQLite,在NuGet中安装必要的Entity Framework包,定义您的实体类,并创建一个DbContext类。这种设置允许对象关系映射,简化C#项目中的数据库交互。
如何使用C#从数据库数据生成PDF文档?
使用IronPDF,您可以通过将HTML转换为PDF在C#中从数据库数据生成PDF文档。这允许您从存储在SQLite数据库中的数据创建格式良好的PDF报告。
哪些工具可以增强C#开发的数据库应用程序?
Iron Suite,其中包括像IronPDF、IronXL、IronOCR和IronBarcode这样的工具,通过提供PDF创建、Excel文件操作、文本识别和条形码生成等功能来增强C#开发的数据库应用。








