
DuckDB C#(對開發者如何理解的工作)
DuckDB.NET 是一個開源的 .NET 綁定 DuckDB 原生程式庫的供應商,設計為與 C# 無縫整合。 它提供了一個 ADO.NET 供應商,使得在 .NET 應用程式中使用 DuckDB(一個低層綁定程式庫)變得容易。 這個套件對於希望在 C# 環境中利用 DuckDB 強大分析能力的開發者來說非常理想。
安裝
安裝 DuckDB.NET 非常簡單。 您可以使用 .NET CLI 將其新增到您的專案中:
dotnet add package DuckDB.NET.Data.Full
或者,您可以通過 Visual Studio 的 NuGet 套件管理器進行安裝。
基本使用
安裝完成後,您可以開始使用 DuckDB.NET 在您的 C# 應用程式中執行 SQL 查詢。 這裡有一個簡單的例子:
using System;
using DuckDB.NET.Data;
class Program
{
static void Main()
{
// Create and open a connection to an in-memory DuckDB database
using var duckdbconnection = new DuckDBConnection("Data Source=:memory:");
duckdbconnection.Open();
// Create a command associated with the connection
using var command = duckdbconnection.CreateCommand();
// Create a table named 'integers'
command.CommandText = "CREATE TABLE integers(foo INTEGER, bar INTEGER);";
command.ExecuteNonQuery();
// Insert some data into the 'integers' table
command.CommandText = "INSERT INTO integers VALUES (3, 4), (5, 6), (7, 8);";
command.ExecuteNonQuery();
// Retrieve the count of rows in the 'integers' table
command.CommandText = "SELECT count(*) FROM integers";
var executeScalar = command.ExecuteScalar();
// Select all values from the 'integers' table
command.CommandText = "SELECT foo, bar FROM integers;";
// Execute the query and process the results
using var reader = command.ExecuteReader();
while (reader.Read())
{
Console.WriteLine($"{reader.GetInt32(0)}, {reader.GetInt32(1)}");
}
}
}Imports System
Imports DuckDB.NET.Data
Module Program
Sub Main()
' Create and open a connection to an in-memory DuckDB database
Using duckdbconnection As New DuckDBConnection("Data Source=:memory:")
duckdbconnection.Open()
' Create a command associated with the connection
Using command = duckdbconnection.CreateCommand()
' Create a table named 'integers'
command.CommandText = "CREATE TABLE integers(foo INTEGER, bar INTEGER);"
command.ExecuteNonQuery()
' Insert some data into the 'integers' table
command.CommandText = "INSERT INTO integers VALUES (3, 4), (5, 6), (7, 8);"
command.ExecuteNonQuery()
' Retrieve the count of rows in the 'integers' table
command.CommandText = "SELECT count(*) FROM integers"
Dim executeScalar = command.ExecuteScalar()
' Select all values from the 'integers' table
command.CommandText = "SELECT foo, bar FROM integers;"
' Execute the query and process the results
Using reader = command.ExecuteReader()
While reader.Read()
Console.WriteLine($"{reader.GetInt32(0)}, {reader.GetInt32(1)}")
End While
End Using
End Using
End Using
End Sub
End Module這個例子展示了如何使用 DuckDB.NET 建立表格、插入資料和查詢資料。
輸出

資料導入
DuckDB.NET 支援從多種格式讀取資料,包括 CSV 和 Parquet 檔案。 以下是如何從 CSV 檔案讀取資料的方式:
command.CommandText = "COPY integers FROM 'example.csv' (FORMAT CSV);";
command.ExecuteNonQuery();command.CommandText = "COPY integers FROM 'example.csv' (FORMAT CSV)"
command.ExecuteNonQuery()與資料框架的整合
DuckDB.NET 也可以與資料框架整合,使您能夠使用熟悉的 SQL 語法操作資料。 這對於資料分析任務特別有用。
結果轉換
您可以將查詢結果轉換為多種格式,例如列表或自訂物件,使您可以輕鬆地在應用程式中使用資料。
var results = new List<(int foo, int bar)>();
// Read and store results to a List
while (reader.Read())
{
results.Add((reader.GetInt32(0), reader.GetInt32(1)));
// You can also use a loop with an index to iterate the results
}Dim results = New List(Of (foo As Integer, bar As Integer))()
' Read and store results to a List
Do While reader.Read()
results.Add((reader.GetInt32(0), reader.GetInt32(1)))
' You can also use a loop with an index to iterate the results
Loop將資料寫入磁碟
DuckDB.NET 支援以多種格式將資料寫入磁碟。 您可以使用 COPY 語句將資料匯出到 CSV 檔案:
command.CommandText = "COPY integers TO 'output.csv' (FORMAT CSV);";
command.ExecuteNonQuery();command.CommandText = "COPY integers TO 'output.csv' (FORMAT CSV)"
command.ExecuteNonQuery()簡介 IronPDF

IronPDF 是一個 C# 的 PDF 程式庫,允許在 .NET 專案中生成、管理和提取 PDF 文件中的內容。 這裡有一些主要特點:
IronPDF 是一個便捷工具,使您能把網頁、URL 和 HTML 轉成 PDF。 最好的部分是? 這些 PDF 看起來就像原來的網頁一樣 - 保留了所有的格式和樣式。 所以,如果您需要從線上的某些東西生成 PDF,例如報告或發票,IronPDF 是您的首選。
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-
HTML 轉成 PDF:
- 將 HTML、CSS 和 JavaScript 內容轉換為 PDF。
- 使用 Chrome 渲染引擎以生成像素級精確的 PDF 文件。
- 從 URL、HTML 檔案或 HTML 字串生成 PDF。
-
影像和內容轉換:
- 將影像轉換為 PDF 文件,或從 PDF 文件中轉換影像。
- 從現有的 PDF 文件中提取文字和影像。
- 支援多種影像格式如 JPG、PNG 等。
-
編輯和操作:
- 設置 PDF 文件的屬性、安全性和權限。
- 向 PDF 新增數位簽名。
- 編輯元資料和修訂歷史。
-
跨平台支援:
- 與 .NET Core (8、7、6、5 和 3.1+)、.NET Standard (2.0+) 及 .NET Framework (4.6.2+) 配合使用。
- 與 Windows、Linux 和 macOS 相容。
- 可在 NuGet 上取得,便於安裝。
使用 IronPDF 和 DuckDB .NET 生成 PDF 文件
首先,按照以下步驟,使用 Visual Studio 建立一個控制台應用程式。

提供專案名稱。

提供 .NET 版本。

安裝 IronPDF 套件。

安裝 DuckDB.NET 套件。

using DuckDB.NET.Data;
using IronPdf;
namespace CodeSample
{
public static class DuckDbDemo
{
public static void Execute()
{
// Instantiate Renderer
var renderer = new ChromePdfRenderer();
var content = "<h1>Demo DuckDb and IronPDF</h1>";
content += "<h2>Create DuckDBConnection</h2>";
content += "<p>new DuckDBConnection(\"Data Source=:memory:\");</p>";
content += "<p></p>";
// Create and open a connection to an in-memory DuckDB database
using var connection = new DuckDBConnection("Data Source=:memory:");
connection.Open();
using var command = connection.CreateCommand();
// Create a table named 'integers'
command.CommandText = "CREATE TABLE integers(book STRING, cost INTEGER);";
command.ExecuteNonQuery();
content += "<p>CREATE TABLE integers(book STRING, cost INTEGER);</p>";
// Insert some data into the 'integers' table
command.CommandText = "INSERT INTO integers VALUES ('book1', 25), ('book2', 30), ('book3', 10);";
command.ExecuteNonQuery();
content += "<p>INSERT INTO integers VALUES ('book1', 25), ('book2', 30), ('book3', 10);</p>";
// Select all values from the 'integers' table
command.CommandText = "SELECT book, cost FROM integers;";
using var reader = command.ExecuteReader();
content += "<p>SELECT book, cost FROM integers;</p>";
// Execute the query and process the results, appending them to the HTML content
while (reader.Read())
{
content += $"<p>{reader.GetString(0)}, {reader.GetInt32(1)}</p>";
Console.WriteLine($"{reader.GetString(0)}, {reader.GetInt32(1)}");
}
// Save data to CSV
content += "<p>Save data to CSV with COPY integers TO 'output.csv' (FORMAT CSV);</p>";
command.CommandText = "COPY integers TO 'output.csv' (FORMAT CSV);";
command.ExecuteNonQuery();
// Generate and save PDF
var pdf = renderer.RenderHtmlAsPdf(content);
pdf.SaveAs("AwesomeDuckDbNet.pdf");
}
}
}Imports DuckDB.NET.Data
Imports IronPdf
Namespace CodeSample
Public Module DuckDbDemo
Public Sub Execute()
' Instantiate Renderer
Dim renderer = New ChromePdfRenderer()
Dim content = "<h1>Demo DuckDb and IronPDF</h1>"
content += "<h2>Create DuckDBConnection</h2>"
content += "<p>new DuckDBConnection(""Data Source=:memory:"");</p>"
content += "<p></p>"
' Create and open a connection to an in-memory DuckDB database
Using connection = New DuckDBConnection("Data Source=:memory:")
connection.Open()
Using command = connection.CreateCommand()
' Create a table named 'integers'
command.CommandText = "CREATE TABLE integers(book STRING, cost INTEGER);"
command.ExecuteNonQuery()
content += "<p>CREATE TABLE integers(book STRING, cost INTEGER);</p>"
' Insert some data into the 'integers' table
command.CommandText = "INSERT INTO integers VALUES ('book1', 25), ('book2', 30), ('book3', 10);"
command.ExecuteNonQuery()
content += "<p>INSERT INTO integers VALUES ('book1', 25), ('book2', 30), ('book3', 10);</p>"
' Select all values from the 'integers' table
command.CommandText = "SELECT book, cost FROM integers;"
Using reader = command.ExecuteReader()
content += "<p>SELECT book, cost FROM integers;</p>"
' Execute the query and process the results, appending them to the HTML content
While reader.Read()
content += $"<p>{reader.GetString(0)}, {reader.GetInt32(1)}</p>"
Console.WriteLine($"{reader.GetString(0)}, {reader.GetInt32(1)}")
End While
End Using
' Save data to CSV
content += "<p>Save data to CSV with COPY integers TO 'output.csv' (FORMAT CSV);</p>"
command.CommandText = "COPY integers TO 'output.csv' (FORMAT CSV);"
command.ExecuteNonQuery()
End Using
End Using
' Generate and save PDF
Dim pdf = renderer.RenderHtmlAsPdf(content)
pdf.SaveAs("AwesomeDuckDbNet.pdf")
End Sub
End Module
End Namespace程式碼解釋
該程式碼旨在展示如何使用 DuckDB.NET 進行資料庫操作,以及使用 IronPDF 生成包含資料庫查詢結果的 PDF 報告。
關鍵組件
-
DuckDB.NET:
- DuckDBConnection: 建立與記憶體中的 DuckDB 資料庫文件的連接("Data Source=:memory:")。 此連接在整個程式碼中都用於執行 SQL 命令。
-
資料庫操作:
- 建表: 定義 SQL 命令(CREATE TABLE integers(book STRING, cost INTEGER);)以建立名為 integers 的表,表中有列 book(STRING)和 cost(INTEGER)。
- 資料插入: 插入行到 integers 表(INSERT INTO integers VALUES ('book1', 25), ('book2', 30), ('book3', 10);)。
- 資料檢索: 執行 SELECT 查詢(SELECT book, cost FROM integers;)以從 integers 表中獲取資料。 檢索到的資料被格式化為 HTML(content)並列印到控制台。
-
使用 IronPDF 生成 PDF:
- 將 HTML 渲染成 PDF: 使用 IronPDF 的 ChromePdfRenderer 將 HTML 內容(content)轉換為 PDF 文件(pdf)。
- 保存 PDF: 將生成的 PDF 保存為 "AwesomeDuckDbNet.pdf" 到當前目錄。
輸出


IronPDF 授權
IronPDF 套件需要授權才能運行。 請在存取套件前在應用程式的開始處新增以下程式碼。
IronPdf.License.LicenseKey = "IRONPDF-KEY";Imports IronPdf
IronPdf.License.LicenseKey = "IRONPDF-KEY"在 IronPDF 的試用授權頁面 上可以獲得試用授權。
結論
DuckDB.NET C# 套件是一個強大的工具,可以將 DuckDB 的分析能力整合到 .NET 應用程式中。 其易用性、支持多種資料格式以及與 C# 的無縫整合,使它成為從事資料密集型應用程式開發的開發者的絕佳選擇。 無論您是在構建資料分析工具、ETL 管道,還是其他資料驅動的應用程式,DuckDB.NET 都能幫助您高效達成目標。

Jacob Mellor是Iron Software的首席技術官,一位在C# PDF技術上開創先河的遠見工程師。作為Iron Software核心程式碼庫的原開發者,他從創立以來就一直在塑造公司的產品架構,與首席執行官Cameron Rimington一起將公司轉變為服務於NASA、特斯拉和全球政府公司的50多名人員的公司。
相關文章


