跳至頁尾內容
.NET 幫助

DuckDB C#(開發者使用指南)

DuckDB.NET是一個開源的 .NET 綁定供應商,用於 DuckDB 原生程式庫,旨在與 C# 無縫整合。 它提供了一個 ADO.NET 提供程序,使得在 .NET 應用程式中使用 DuckDB(一個底層綁定程式庫)變得容易。 對於希望在 C# 環境中利用 DuckDB 強大分析功能的開發人員來說,此軟體套件是理想之選。

安裝

安裝 DuckDB.NET 非常簡單。 您可以使用 .NET CLI 將其新增至您的專案:

dotnet add package DuckDB.NET.Data.Full
dotnet add package DuckDB.NET.Data.Full
SHELL

或者,您也可以透過 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)}");
        }
    }
}
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)}");
        }
    }
}
$vbLabelText   $csharpLabel

本範例示範如何使用 DuckDB.NET 建立表格、插入資料和查詢資料。

輸出

DuckDB C#(開發者使用指南):圖 1 - 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();
$vbLabelText   $csharpLabel

與數據框集成

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

將資料寫入磁碟

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

IronPDF簡介

DuckDB C#(開發者使用指南):圖 2 - 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");
    }
}
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
  1. HTML 轉 PDF: 將 HTML、CSS 和 JavaScript 內容轉換為 PDF。
    • 用於實現像素級完美 PDF 文件的 Chrome 渲染引擎。
    • 從 URL、HTML 檔案或 HTML 字串產生 PDF。

2.圖片和內容轉換:

  • 將影像轉換為 PDF 文檔,反之亦然。
  • 從現有 PDF 文件中提取文字和圖像。
  • 支援多種影像格式,如 JPG、PNG 等。

3.編輯和篡改:

  • 設定 PDF 文件的屬性、安全性和權限。
  • 為PDF檔案新增數位簽章。
  • 編輯元資料和修訂歷史。

4.跨平台支援:

  • 可與 .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 建立一個控制台應用程式,如下所示。

DuckDB C#(開發者使用指南):圖 3 - 控制台應用程式

請提供項目名稱。

DuckDB C#(開發者使用指南):圖 4 - 專案配置

請提供.NET版本。

DuckDB C#(開發者使用指南):圖 5 - 目標框架

安裝 IronPDF 軟體包。

DuckDB C#(開發者使用指南):圖 6 - IronPDF

安裝 DuckDB.NET 軟體包。

DuckDB C#(開發者使用指南):圖 7 - 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");
        }
    }
}
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");
        }
    }
}
$vbLabelText   $csharpLabel

程式碼解釋

程式碼旨在展示如何使用 DuckDB.NET 進行資料庫操作,以及如何使用 IronPDF 產生包含資料庫查詢結果的 PDF 報告。

關鍵組成部分

  1. DuckDB.NET:
    • DuckDBConnection:建立與記憶體中的 DuckDB 資料庫檔案("資料來源=:memory:")的連線。 整個程式碼都使用此連線來執行 SQL 命令。

2.資料庫操作: *建立表格:*定義一個 SQL 指令(CREATE TABLE integers(book STRING, cost INTEGER);)來建立一個名為 integers 的表,其中包含 book(STRING)和 cost(INTEGER)欄位。 資料插入:**向整數表中插入行(INSERT INTO integers VALUES ('book1', 25), ('book2', 30), ('book3', 10);)。 *資料擷取:執行 SELECT 查詢(SELECT book, cost FROM integers;)從整數表中取得資料。 檢索到的資料被格式化為 HTML(內容)並列印到控制台。

3.使用 IronPDF 產生 PDF: *將 HTML 渲染為 PDF:*使用 IronPDF 中的 ChromePdfRenderer 將 HTML 內容(內容)轉換為 PDF 文件(pdf)。 儲存 PDF:**將產生的 PDF 儲存為目前目錄中的"AwesomeDuckDbNet.pdf"。

輸出

DuckDB C#(開發者使用指南):圖 8 - 控制台輸出

PDF

DuckDB C#(開發者使用指南):圖 9 - PDF 輸出

IronPDF 許可

IronPDF軟體包需要許可證才能運作。 在應用程式啟動時,請在存取該套件之前,請新增以下程式碼。

IronPdf.License.LicenseKey = "IRONPDF-KEY";
IronPdf.License.LicenseKey = "IRONPDF-KEY";
$vbLabelText   $csharpLabel

IronPDF 的試用許可證頁面提供試用許可證。

結論

DuckDB.NET C# 套件是一個強大的工具,可將 DuckDB 的分析功能整合到 .NET 應用程式中。 它易於使用,支援各種數據格式,並與 C# 無縫集成,使其成為從事數據密集型應用程式開發的開發人員的絕佳選擇。 無論您是建立資料分析工具、ETL 管道還是其他資料驅動型應用程序,DuckDB.NET 都能幫助您有效率地實現目標。

常見問題解答

DuckDB.NET 在 C# 應用程式中用於什麼用途?

DuckDB.NET 用於將 DuckDB 本地程式庫整合到 C# 應用程式中,透過 ADO.NET 提供者為開發人員提供強大的分析功能。

如何在 C# 專案中安裝 DuckDB.NET?

您可以使用 .NET CLI 指令dotnet add package DuckDB.NET.Data.Full或透過 Visual Studio 中的 NuGet 套件管理員安裝 DuckDB.NET。

如何使用 DuckDB.NET 執行 SQL 查詢?

您可以使用 DuckDB.NET 執行 SQL 查詢,方法是使用DuckDBConnection建立連接,然後執行 SQL 命令來建立表格、插入和檢索資料。

DuckDB.NET 是否支援讀取 CSV 和 Parquet 檔案中的資料?

是的,DuckDB.NET 支援從各種格式(包括 CSV 和 Parquet 檔案)匯入數據,從而可以在 C# 應用程式中無縫整合和操作這些資料類型。

如何在C#中將HTML轉換為PDF?

您可以使用 IronPDF 的RenderHtmlAsPdf方法將 HTML 字串轉換為 PDF。您也可以使用RenderHtmlFileAsPdf將 HTML 檔案轉換為 PDF。

使用 DuckDB.NET 處理資料密集型專案有哪些好處?

DuckDB.NET 提供強大的分析功能,支援基於 SQL 的資料操作,並且可以輕鬆與 C# 應用程式集成,使其成為資料密集型專案的理想選擇。

如何將 DuckDB.NET 與資料幀整合?

DuckDB.NET 可以與資料幀集成,實現基於 SQL 的資料操作,這對於執行複雜的資料分析任務尤其有用。

如何使用 DuckDB.NET 將資料匯出到 CSV 檔案?

您可以使用 DuckDB.NET 的COPY語句將資料匯出到 CSV 檔案。例如,使用COPY integers TO 'output.csv' (FORMAT CSV);可以將表格資料匯出到 CSV 檔案。

IronPDF 支援哪些平台?

IronPDF 支援 .NET Core(8、7、6、5 和 3.1+)、.NET Standard(2.0+)和 .NET Framework(4.6.2+),並且相容於 Windows、Linux 和 macOS。

我能否將 DuckDB.NET 和 IronPDF 結合使用來產生報告?

是的,您可以將 DuckDB.NET 用於資料庫操作,將 IronPDF 用於產生 PDF 報告,利用 DuckDB 的資料庫功能和 IronPDF 的 PDF 產生功能。

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

Jacob Mellor 是 Iron Software 的首席技術官,也是一位富有遠見的工程師,率先開發了 C# PDF 技術。作為 Iron Software 核心程式碼庫的最初開發者,他自公司成立之初便參與塑造了其產品架構,並與執行長 Cameron Rimington 一起將其發展成為一家擁有 50 多名員工、服務於 NASA、特斯拉和全球政府機構的公司。

Jacob 於 1998 年至 2001 年在曼徹斯特大學獲得土木工程一級榮譽學士學位。 1999 年,他在倫敦創辦了自己的第一家軟體公司;2005 年,他創建了自己的第一個 .NET 元件。此後,他專注於解決微軟生態系統中的複雜問題。

他的旗艦產品 IronPDF 和 IronSuite .NET 庫在全球 NuGet 上的安裝量已超過 3000 萬次,其基礎程式碼持續為全球開發者工具提供支援。憑藉 25 年的商業經驗和 41 年的程式設計專長,Jacob 始終致力於推動企業級 C#、Java 和 Python PDF 技術的創新,同時指導下一代技術領導者。