跳過到頁腳內容
.NET幫助

C# SQLite(開發者的工作原理)

SQLite 簡介

SQLite 是一個獨立、無伺服器、零組態的資料庫引擎,用於各種應用程式,包括桌上型電腦、網頁和行動應用程式。 在本教程中,我們將深入介紹如何使用 SQLite 與 C#。 使用簡單易懂的範例,您將學會如何建立、管理 SQLite 資料庫,並與之互動。

什麼是 SQLite?

SQLite 是一種輕量且高效的資料庫,可將資料儲存於單一檔案中。與傳統資料庫不同,它不需要獨立的伺服器。 這使得它成為需要資料庫的應用程式的最佳選擇,而不需要複雜的完整資料庫系統。

Setting Up SQLite in C#

使用 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;"
$vbLabelText   $csharpLabel

連接物件

您可以使用 SQLiteConnection 類別從 System.Data.SQLite 命名空間建立連接物件。

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()
$vbLabelText   $csharpLabel

建立表格

建立表格

在使用任何資料庫時,建立資料表是最基本的步驟。 以下是如何使用 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()
$vbLabelText   $csharpLabel
  • 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()
$vbLabelText   $csharpLabel

參數化指令

參數化指令可以保護您的應用程式免於 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()
$vbLabelText   $csharpLabel

擷取資料

選擇聲明

若要從資料庫表中擷取資料,請使用 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
$vbLabelText   $csharpLabel

進階功能

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
$vbLabelText   $csharpLabel

Object-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 Class
$vbLabelText   $csharpLabel

3.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 Class
$vbLabelText   $csharpLabel

4.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
$vbLabelText   $csharpLabel

使用 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()
$vbLabelText   $csharpLabel

擷取 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 parser
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 parser
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

' 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
$vbLabelText   $csharpLabel

與其他資料提供者合作。

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
$vbLabelText   $csharpLabel

在使用 SQLite 資料庫時,IronPDF 可說是不可或缺的工具。 您可以從 SQLite 資料庫的資料產生 PDF 報告,讓資料的呈現與分享無懈可擊。

IronXL:Excel 檔案管理變得簡單

探索 IronXL for Excel 整合,它可讓開發人員毫不費力地讀取、寫入和處理 Excel 檔案。 它與 XLS、XLSX 等相容,是處理試算表資料的理想工具。 您可以讀取 Excel 檔案、處理檔案,甚至從頭建立新檔案。 IronXL 的功能與資料庫管理(包括 SQLite)整合得很好,可以匯出和匯入資料。

IronOCR: Optical Character Recognition in 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 資料庫或任何其他領域。

更吸引人的是,這些產品都提供免費試用,讓您有充足的時間探索和了解它們提供的豐富功能。一旦您決定繼續使用這些工具,許可證費用為每個產品 $999 起。 您也可以只花兩個單獨產品的價格,購買完整的 Iron Suite 套件。

常見問題解答

如何在 C# 專案中使用 NuGet 設定 SQLite?

要在 C# 專案中使用 NuGet 設定 SQLite,請打開 Visual Studio 並建立一個新的控制台應用程式。進入 NuGet 套件管理器,搜尋 'SQLite' 並安裝該套件。這將 SQLite 函式庫整合到您的專案中以進行資料庫操作。

在 C# 應用程式中使用 SQLite 的好處是什麼?

SQLite 是一個輕量級的無伺服器資料庫引擎,將資料存儲在單個檔案中,這使得它成為需要簡單高效資料庫解決方案而不用複雜傳統資料庫系統應用程式的理想選擇。

如何在 C# 中連接到 SQLite 資料庫?

在 C# 中可以通過創建一個類似 Data Source=mydatabase.db; 的連接字串,並利用 System.Data.SQLite 命名空間的 SQLiteConnection 類來建立並打開連接。

如何使用 C# 執行 CRUD 操作於 SQLite 資料庫?

通過佈署 SQL 命令如 INSERTSELECTUPDATEDELETE,您可以在 C# 中執行 SQLite 資料庫的 CRUD 操作。這些命令可以通過 SQLiteCommand 物件來執行。

交易在 SQLite 中扮演什麼角色?

SQLite 中的交易允許將多個操作作為單個原子動作執行。您可以用 connection.BeginTransaction() 開始一個交易,執行必要的操作,然後根據結果提交或回滾交易。

如何在 C# 專案中使用 Entity Framework 與 SQLite?

要使用 Entity Framework 與 SQLite,通過 NuGet 安裝必要的 Entity Framework 套件,定義您的實體類別,並創建一個 DbContext 類。這個設定允許進行物件關係映射,簡化 C# 專案中的資料庫操作。

如何使用 C# 從資料庫資料生成 PDF 文件?

使用 IronPDF,您可以透過將 HTML 轉換為 PDF,從資料庫資料生成 PDF 文件。這允許您從存儲在 SQLite 資料庫中的資料創建格式良好的 PDF 報告。

有哪些工具可以增強 C# 的資料庫應用程式開發?

Iron Suite 包含如 IronPDF、IronXL、IronOCR 和 IronBarcode 的工具,通過提供如 PDF 生成、Excel 檔案操作、文本識別和條碼生成的功能來增強 C# 對資料庫應用程式的開發。

Jacob Mellor, Team Iron 首席技術官
首席技術官

Jacob Mellor是Iron Software的首席技術官,也是開創C# PDF技術的前瞻性工程師。作為Iron Software核心代碼庫的原始開發者,他自公司成立以來就塑造了公司的產品架構,並與CEO Cameron Rimington將公司轉型為服務NASA、Tesla以及全球政府機構的50多人公司。

Jacob擁有曼徹斯特大學土木工程一級榮譽學士學位(1998年–2001年)。他於1999年在倫敦開立首家軟體公司,並於2005年建立了他的第一個.NET組件,專注於解決Microsoft生態系統中的複雜問題。

他的旗艦作品IronPDF和Iron Suite .NET程式庫全球已獲得超過3000萬次NuGet安裝,他的基礎代碼不斷在全球各地驅動開發者工具。擁有25年以上的商業經驗和41年的編碼專業知識,Jacob仍然專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

鋼鐵支援團隊

我們每週 5 天,每天 24 小時在線上。
聊天
電子郵件
打電話給我