.NET幫助 C# SQLite(開發者的工作原理) Curtis Chau 更新日期:7月 28, 2025 Download IronPDF NuGet 下載 DLL 下載 Windows 安裝程式 Start Free Trial Copy for LLMs Copy for LLMs Copy page as Markdown for LLMs Open in ChatGPT Ask ChatGPT about this page Open in Gemini Ask Gemini about this page Open in Grok Ask Grok about this page Open in Perplexity Ask Perplexity about this page Share Share on Facebook Share on X (Twitter) Share on LinkedIn Copy URL Email article SQLite 介紹 SQLite 是一個獨立的、無伺服器的、零配置的數據庫引擎,用於桌面、Web 和移動應用程序等各種應用中。 在本教程中,我們將深入介紹如何在 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;" $vbLabelText $csharpLabel 連接對象 您可以使用 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() $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 整數主鍵: 將 '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 語句 要從數據庫表中檢索數據,請使用 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 使用實體框架進行對象關係映射 (ORM) 實體框架 (EF) 是 .NET 生態系統中一個廣泛使用的 ORM 工具。 它通過允許開發者使用領域專用對象來處理關係數據,簡化了數據庫編程。 以下是如何將實體框架與 SQLite 一起使用。 1. 安裝實體框架 首先,確保您已安裝針對 SQLite 的實體框架 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 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 操作 實體框架簡化了創建、讀取、更新和刪除 (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 使用實體框架進行讀取、更新和刪除記錄同樣流暢且簡單,允許生成簡潔且可維護的代碼。 使用 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 Suit:一套強大的庫 在探索過 C# 中的 SQLite 和邏輯運算符之後,是時候介紹一套出色的工具集了,它們補充並增強了 .NET 環境中的開發體驗。 Iron Suit 是一系列強大的庫,包含 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 $vbLabelText $csharpLabel IronPDF 在處理 SQLite 數據庫時可能是一個必要的工具。 您可以從 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 都是極佳的選擇。 Iron Suit,包含 IronPDF、IronXL、IronOCR 和 IronBarcode,是一個寶庫,擴展了 C# 開發項目的功能,無論您是在使用 SQLite 數據庫還是其他領域。 更具吸引力的是這些產品中的每一個都提供Iron Software 產品的免費試用版,讓您有充足的時間來探索和了解它們提供的廣泛功能。一旦您決定繼續使用這些工具,許可證從每個產品 $799 開始。 您也可以以僅僅是兩個單獨產品價格的方式購買完整的 Iron Suit 包。 常見問題解答 如何在 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 命令如 INSERT、SELECT、UPDATE 和 DELETE,您可以在 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 Suit 包含如 IronPDF、IronXL、IronOCR 和 IronBarcode 的工具,通過提供如 PDF 生成、Excel 檔案操作、文本識別和條碼生成的功能來增強 C# 對資料庫應用程式的開發。 Curtis Chau 立即與工程團隊聊天 技術作家 Curtis Chau 擁有卡爾頓大學計算機科學學士學位,專注於前端開發,擅長於 Node.js、TypeScript、JavaScript 和 React。Curtis 熱衷於創建直觀且美觀的用戶界面,喜歡使用現代框架並打造結構良好、視覺吸引人的手冊。除了開發之外,Curtis 對物聯網 (IoT) 有著濃厚的興趣,探索將硬體和軟體結合的創新方式。在閒暇時間,他喜愛遊戲並構建 Discord 機器人,結合科技與創意的樂趣。 相關文章 更新日期 9月 4, 2025 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新日期 9月 4, 2025 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 更新日期 8月 5, 2025 C#開關模式匹配(對開發者來說是如何工作的) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 SignalR C#(開發者的工作原理)C# 網頁應用(開發者的工...