C# SQLite(開發者的工作原理)
SQLite 簡介
SQLite 是一個獨立、無伺服器、零組態的資料庫引擎,用於各種應用程式,包括桌上型電腦、網頁和行動應用程式。 在本教程中,我們將深入介紹如何使用 SQLite 與 C#。 使用簡單易懂的範例,您將學會如何建立、管理 SQLite 資料庫,並與之互動。
什麼是 SQLite?
SQLite 是一種輕量且高效的資料庫,可將資料儲存於單一檔案中。與傳統資料庫不同,它不需要獨立的伺服器。 這使得它成為需要資料庫的應用程式的最佳選擇,而不需要複雜的完整資料庫系統。
在 C# 中設定 SQLite;。
使用 NuGet 套件管理員
若要在 C# 專案中使用 SQLite,您需要安裝必要的 SQLite 函式庫。 這可以透過 NuGet Package Manager 來完成。
1.開啟 Visual Studio 並建立新的控制台應用程式。 2.在專案上按一下滑鼠右鍵,然後選擇 "管理 NuGet 套件"。 3.搜尋"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 TryObject-Relational Mapping (ORM) with Entity Framework。
Entity Framework (EF) 是 .NET 生態系統中廣泛使用的 ORM 工具。 它允許開發人員使用特定領域的物件來處理關係資料,從而簡化資料庫程式設計。 以下是如何使用 Entity Framework 與 SQLite。
1.安裝 Entity Framework
首先,確保您已安裝 SQLite 專用的 Entity Framework NuGet 套件:
1.在 Visual Studio 中開啟 NuGet Package Manager。 2.搜尋"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 資料
您可以在 C# 中使用標準的 XML 解析技術擷取和處理 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 和圖片,使其成為有力的工具。 請參閱本教學 Converting HTML to PDF with IronPDF 的逐步指南。
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 for Excel 整合,它可讓開發人員毫不費力地讀取、寫入和處理 Excel 檔案。 它與 XLS、XLSX 等相容,是處理試算表資料的理想工具。 您可以讀取 Excel 檔案、處理檔案,甚至從頭建立新檔案。 IronXL 的功能與資料庫管理(包括 SQLite)整合得很好,可以匯出和匯入資料。
IronOCR:C# 中的光學字元識別;
使用 IronOCR for Text Recognition,從影像和 PDF 檔案掃描文字變得輕而易舉。 這是一個多功能的 OCR(光學字元辨識)函式庫,可辨識來自各種來源的文字。
想像一下將掃描的文件儲存在 SQLite 資料庫中,並使用 IronOCR 來擷取和辨識這些文件中的文字。 提供強大的文字檢索和搜尋功能,可能性無限。
IronBarcode:終極條碼生成和讀取程式庫。
透過 透過 IronBarcode 強大的條碼整合,讓條碼產生和讀取變得簡單。 它支援多種條碼格式,並為所有條碼相關需求提供強大的 API。 IronBarcode 可在使用 SQLite 的應用程式中扮演重要角色,其中條碼可能代表產品或其他資料實體。 從 SQLite 資料庫中儲存和擷取 BarCode 可增強資料的完整性,並方便快速存取。
結論
SQLite 是一個功能強大但輕量級的資料庫引擎,無論對初學者或專業人士都非常適合。從建立資料表和插入資料行到管理交易和預防 SQL 注入攻擊,SQLite 提供了許多功能。 無論您是要建立主控台或行動應用程式,或是需要處理外鍵和資料集,SQLite 都是絕佳的選擇。
Iron Suit 由 IronPDF、IronXL、IronOCR 和 IronBarcode 組成,是擴展 C# 開發專案功能的工具寶庫,無論您使用的是 SQLite 資料庫或任何其他領域。
更吸引人的是,這些產品都提供 免費試用 Iron Software 產品,讓您有充裕的時間探索和瞭解它們所提供的大量功能。一旦您決定繼續使用這些工具,每項產品的授權起點為 $799 。 您也可以只花兩個單獨產品的價格,購買完整的 Iron Suite 套件。
常見問題解答
如何使用 NuGet 在 C# 專案中設定 SQLite?
若要使用 NuGet 在 C# 專案中設定 SQLite,請開啟 Visual Studio 並建立新的 Console Application。存取 NuGet 套件管理員,搜尋「SQLite」,然後安裝套件。這將會把 SQLite 函式庫整合到您的專案中,以便進行資料庫操作。
C# 應用程式使用 SQLite 有什麼好處?
SQLite 是一種輕量級、無伺服器的資料庫引擎,可將資料儲存於單一檔案中,非常適合需要簡單有效的資料庫解決方案的應用程式,而無需傳統資料庫系統的複雜性。
如何用 C# 連接到 SQLite 資料庫?
您可以在 C# 中透過建立類似 Data Source=mydatabase.db; 的連線字串,並使用 System.Data.SQLite 命名空間中的 SQLiteConnection 類來建立和開啟連線,以連線至 SQLite 資料庫。
如何使用 C# 在 SQLite 資料庫上執行 CRUD 操作?
使用 SQL 指令,例如 INSERT、SELECT、UPDATE 和 DELETE,您可以在 C# 中對 SQLite 資料庫執行 CRUD 操作。這些指令可以使用 SQLiteCommand 物件來執行。
事務在 SQLite 中扮演什麼角色?
SQLite 中的事務允許以單一原子動作執行多個作業。您可以使用 connection.BeginTransaction() 開始一個事務,執行必要的作業,然後根據結果提交或回溯事務。
如何在 C# 專案中使用 Entity Framework 與 SQLite?
要在 SQLite 中使用 Entity Framework,請透過 NuGet 安裝必要的 Entity Framework 套件,定義您的實體類別,並建立 DbContext 類別。此設定允許物件關聯映射,簡化 C# 專案中的資料庫互動。
如何使用 C# 從資料庫資料生成 PDF 文件?
使用 IronPDF,您可以通過將 HTML 轉換為 PDF,從 C# 中的資料庫數據生成 PDF 文件。這可讓您從 SQLite 資料庫中儲存的資料建立格式良好的 PDF 報表。
哪些工具可以增強資料庫應用程式的 C# 開發?
Iron Suite 包括 IronPDF、IronXL、IronOCR 和 IronBarcode 等工具,透過提供 PDF 建立、Excel 檔案處理、文字辨識和條碼產生等功能,強化資料庫應用程式的 C# 開發。







