跳至頁尾內容
開發者更新

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

SQLite簡介

SQLite是一個自包含、無伺服器、零配置的資料庫引擎,用於各種應用程式,包括桌面、網頁和移動應用程式。 在本教程中,我們將深入探討如何使用SQLite與C#。 透過簡單且易於理解的範例,您將學習如何建立、管理和與SQLite資料庫互動。

什麼是SQLite?

SQLite是一種輕量級且高效的資料庫,它將資料儲存在單個文件中。不像傳統資料庫,它不需要單獨的伺服器。 這使得它成為需要資料庫但不需要完全成熟資料庫系統的應用程式的理想選擇。

Setting Up SQLite in C

使用NuGet包管理器

為了在C#項目中使用SQLite,您需要安裝所需的SQLite程式庫。 這可以通過NuGet包管理器完成。

  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

連接物件

您可以使用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

使用Entity Framework的物件關係映射(ORM)

Entity Framework(EF)是.NET生態系統中廣泛使用的ORM工具。 它通過允許開發人員使用特定於域的物件來操作關係資料來簡化資料庫編程。 這是如何使用Entity Framework與SQLite的方法。

1. 安裝Entity Framework

首先,確保您已經安裝了特定於SQLite的Entity Framework NuGet包:

  1. 在Visual Studio中打開NuGet包管理器。
  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 Suit:一組強大的程式庫

在探索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文件、URLs和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 Integration,該工具允許開發人員輕鬆讀取、寫入和操作Excel文件。 它與XLS、XLSX等相容,使其成為處理電子表格資料的理想工具。 您可以讀取Excel文件、操作它們,甚至從頭建立新文件。 IronXL的功能很好地與資料庫管理整合,包含SQLite在內的資料的匯出和導入。

IronOCR: Optical Character Recognition in C

使用IronOCR for Text Recognition,從圖像和PDF文件中掃描文字變得輕而易舉。 它是一個用途廣泛的OCR(光學字元辨識)程式庫,能夠識別來自各種來源的文字。

想像一下在SQLite資料庫中儲存掃描的文件,並使用IronOCR檢索和識別這些文件中的文字。 這些可能性是無限的,提供強大的文字檢索和搜索功能。

IronBarcode:最終的條碼生成和閱讀程式庫

使用Powerful Barcode Integration via IronBarcode,條碼生成和閱讀變得簡單。 它支持多種條碼格式,並為所有與條碼相關的需求提供強大的API。 在使用SQLite的應用程式中,IronBarcode可以扮演關鍵角色,其中條碼可能代表產品或其他資料實體。 從SQLite資料庫中儲存和檢索條碼增強了資料完整性並促進快速存取。

結論

SQLite是一個強大而輕便的資料庫引擎,非常適合初學者和專業人士。從建立表到插入行,再到管理事務和防止SQL注入攻擊,SQLite提供了許多功能。 無論您是構建控制台還是移動應用程式,還是需要使用外鍵和資料集,SQLite都是理想的選擇。

Iron Suit,包括IronPDF、IronXL、IronOCR和IronBarcode,是一個工具寶庫,可擴展您的C#開發專案的能力,無論您是在使用SQLite資料庫還是任何其他領域。

更具吸引力的是,這些產品中的每一個都提供Iron Software產品的免費試用,讓您有充足的時間去探索和了解它們提供的廣泛功能。一旦您決定繼續使用這些工具,授權價格從$999每個產品開始。 您還可以以兩個單個產品的價格購買完整的Iron Suit套裝。

常見問題

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

要在C#專案中使用NuGet設定SQLite,請打開Visual Studio並建立一個新的控制台應用程式。存取NuGet軟體包管理器,搜索“SQLite”,然後安裝該軟體包。這將整合SQLite程式庫進入您的專案中以進行資料庫操作。

使用SQLite對C#應用程式有什麼好處?

SQLite是一種輕量、無伺服器的資料庫引擎,將資料儲存在單一檔案中,對於需要簡單且高效資料庫解決方案的應用程式來說非常理想,無需傳統資料庫系統的複雜性。

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

您可以透過建立一個連接字串,例如 Data Source=mydatabase.db; 並使用來自 System.Data.SQLite 命名空間的 SQLiteConnection 類來建立和打開連接來連接到SQLite資料庫。

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

使用諸如 INSERTSELECTUPDATEDELETE 之類的SQL命令,您可以在C#中對SQLite資料庫執行CRUD操作。這些命令可以使用 SQLiteCommand 物件執行。

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

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

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

要在C#專案中使用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核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。

Jacob擁有曼徹斯特大學的土木工程一等榮譽學士學位(BEng),於1998-2001年之間獲得。在1999年於倫敦創辦他的第一家軟體公司並於2005年建立了他的第一批.NET元組件後,他專注於解決Microsoft生態系統中的複雜問題。

他的旗艦IronPDF和Iron Suite .NET程式庫在全球獲得了超過3000萬次NuGet安裝依據,他的基礎程式碼基繼續支援著世界各地開發者使用的工具。擁有25年的商業經驗和41年的程式設計專業知識,他仍專注於推動企業級C#、Java和Python PDF技術的創新,同時指導下一代技術領導者。

Iron 支援團隊

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