.NET幫助 C# SQLite(開發者的工作原理) Jacob Mellor 更新:2025年7月28日 下載 IronPDF NuGet 下載 DLL 下載 Windows Installer 開始免費試用 LLM副本 LLM副本 將頁面複製為 Markdown 格式,用於 LLMs 在 ChatGPT 中打開 請向 ChatGPT 諮詢此頁面 在雙子座打開 請向 Gemini 詢問此頁面 在 Grok 中打開 向 Grok 詢問此頁面 打開困惑 向 Perplexity 詢問有關此頁面的信息 分享 在 Facebook 上分享 分享到 X(Twitter) 在 LinkedIn 上分享 複製連結 電子郵件文章 SQLite簡介 SQLite 是一個獨立的、無伺服器的、零配置的資料庫引擎,可用於各種應用程序,包括桌面應用程式、Web 應用程式和行動應用程式。 在本教程中,我們將深入探討如何在 C# 中使用 SQLite。 透過簡單易懂的範例,您將學習如何建立、管理和使用 SQLite 資料庫。 什麼是 SQLite? SQLite 是一種輕量級且高效的資料庫,它將資料儲存在單一檔案中。與傳統資料庫不同,它不需要單獨的伺服器。 這使其成為需要資料庫但又不想使用功能齊全的資料庫系統的應用程式的絕佳選擇。 Setting Up SQLite in C 使用NuGet套件管理器 要在 C# 專案中使用 SQLite,您需要安裝必要的 SQLite 程式庫。 這可以透過NuGet套件管理器完成。 開啟 Visual Studio 並建立一個新的控制台應用程式。 右鍵點選項目,然後選擇"管理NuGet套件"。 搜尋"SQLite"並安裝該軟體包。 建立聯繫 連接字串 連接字串是指定資料來源及其連接方式資訊的字串。 在 SQLite 中,連接字串通常如下所示: string connectionString = "Data Source=mydatabase.db;"; string connectionString = "Data Source=mydatabase.db;"; $vbLabelText $csharpLabel 連接物件 您可以使用 @@--CODE-525--CODE-524--CODE-525 命名空間中的 @@--CODE-524--CODE-525 類別建立連接物件。 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(); $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(); $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(); $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(); $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"]); } $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 } $vbLabelText $csharpLabel 使用 Entity Framework 進行物件關聯映射 (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; } } $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;"); } } $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(); } $vbLabelText $csharpLabel 使用 Entity Framework 讀取、更新和刪除記錄同樣簡單便捷,因此可以編寫簡潔且易於維護的程式碼。 使用 XML 檔案和其他資料提供者 SQLite 不僅限於關聯式資料; 它還提供了處理其他資料類型(包括 XML 檔案)的靈活性。 1. 儲存 XML 數據 您可以將 XML 資料儲存在 SQLite 資料庫中。 如果您處理配置資料或其他層級結構,這可能會很有用。 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(); $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 $vbLabelText $csharpLabel 與其他數據提供者合作 SQLite 還能與各種資料提供者良好集成,從而實現互通性和靈活性。 這意味著您可以無縫切換不同的資料庫,甚至可以在單一應用程式中組合不同的資料來源。 隆重介紹鋼鐵戰衣:一套強大的庫 在探索了 SQLite 和 C# 中的邏輯運算子之後,現在是時候介紹一系列出色的工具,它們可以補充和增強.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"); } } $vbLabelText $csharpLabel 在處理 SQLite 資料庫時, IronPDF可能是一個必不可少的工具。 您可以從 SQLite 資料庫資料產生 PDF 報告,從而實現無縫的資料展示和共用。 IronXL:輕鬆管理 Excel 文件 探索IronXL for Excel Integration ,它允許開發人員輕鬆地讀取、寫入和操作 Excel 檔案。 它相容於 XLS、XLSX 等多種格式,是處理電子表格資料的理想工具。 您可以讀取 Excel 文件、修改 Excel 文件,甚至從頭開始建立新文件。 IronXL 的功能與資料庫管理(包括 SQLite)整合良好,可用於匯出和匯入資料。 IronOCR: Optical Character Recognition in 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 起。 您也可以以兩件單獨產品的價格購買完整的鋼鐵戰衣套裝。 常見問題解答 如何在 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 Suite 包含如 IronPDF、IronXL、IronOCR 和 IronBarcode 的工具,通過提供如 PDF 生成、Excel 檔案操作、文本識別和條碼生成的功能來增強 C# 對資料庫應用程式的開發。 Jacob Mellor 立即與工程團隊聊天 首席技術官 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技術的創新,同時指導下一代技術領導者。 相關文章 更新2026年2月20日 銜接 CLI 簡化與 .NET : 使用 Curl DotNet 與 IronPDF for .NET Jacob Mellor 藉由 CurlDotNet 彌補了這方面的不足,CurlDotNet 是為了讓 .NET 生態系統能熟悉 cURL 而建立的函式庫。 閱讀更多 更新2025年12月20日 RandomNumberGenerator C# 使用RandomNumberGenerator C#類可以幫助將您的PDF生成和編輯項目提升至新水準 閱讀更多 更新2025年12月20日 C#字符串等於(它如何對開發者起作用) 當結合使用強大的PDF庫IronPDF時,開關模式匹配可以讓您構建更智能、更清晰的邏輯來進行文檔處理 閱讀更多 SignalR C#(開發者的工作原理)C# 網頁應用(開發者的工...
更新2026年2月20日 銜接 CLI 簡化與 .NET : 使用 Curl DotNet 與 IronPDF for .NET Jacob Mellor 藉由 CurlDotNet 彌補了這方面的不足,CurlDotNet 是為了讓 .NET 生態系統能熟悉 cURL 而建立的函式庫。 閱讀更多