푸터 콘텐츠로 바로가기
.NET 도움말

DuckDB C# (How It Works For Developers)

DuckDB.NET is an open-source provider of .NET bindings for the DuckDB native library, designed to integrate seamlessly with C#. It provides an ADO.NET provider, making it easy to use DuckDB, a low-level bindings library, within .NET applications. This package is ideal for developers looking to leverage DuckDB’s powerful analytical capabilities in a C# environment.

Installation

Installing DuckDB.NET is straightforward. You can add it to your project using the .NET CLI:

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

Alternatively, you can install it via the NuGet Package Manager in Visual Studio.

Basic Usage

Once installed, you can start using DuckDB.NET to execute SQL queries within your C# application. Here’s a simple example:

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

This example demonstrates how to create a table, insert data, and query the data using DuckDB.NET.

Output

DuckDB C# (How It Works For Developers): Figure 1 - DuckDB.NET Console Output

Data Ingestion

DuckDB.NET supports reading data from various formats, including CSV and Parquet files. Here’s how you can read data from a CSV file:

command.CommandText = "COPY integers FROM 'example.csv' (FORMAT CSV);";
command.ExecuteNonQuery();
command.CommandText = "COPY integers FROM 'example.csv' (FORMAT CSV);";
command.ExecuteNonQuery();
$vbLabelText   $csharpLabel

Integration with DataFrames

DuckDB.NET can also integrate with data frames, allowing you to manipulate data using familiar SQL syntax. This is particularly useful for data analysis tasks.

Result Conversion

You can convert query results to various formats, such as lists or custom objects, making it easy to work with the data in your application:

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

Writing Data to Disk

DuckDB.NET supports writing data to disk in various formats. You can use the COPY statement to export data to a CSV file:

command.CommandText = "COPY integers TO 'output.csv' (FORMAT CSV);";
command.ExecuteNonQuery();
command.CommandText = "COPY integers TO 'output.csv' (FORMAT CSV);";
command.ExecuteNonQuery();
$vbLabelText   $csharpLabel

Introduction to IronPDF

DuckDB C# (How It Works For Developers): Figure 2 - IronPDF

IronPDF is a C# PDF library that allows the generation, management, and extraction of content from PDF documents in .NET projects. Here are some key features:

IronPDF is a handy tool that lets you turn webpages, URLs, and HTML to PDF. The best part? The PDFs look exactly like the original web pages – keeping all the formatting and style. So, if you need to make a PDF from something online, like a report or an invoice, IronPDF is your go-to.

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 to PDF Conversion:

    • Convert HTML, CSS, and JavaScript content to PDFs.
    • Chrome Rendering Engine for pixel-perfect PDF documents.
    • Generate PDFs from URLs, HTML files, or HTML strings.
  2. Image and Content Conversion:

    • Convert images to and from PDF docs.
    • Extract text and images from existing PDF docs.
    • Support for various image formats like JPG, PNG, etc.
  3. Editing and Manipulation:

    • Set properties, security, and permissions for PDF docs.
    • Add digital signatures to PDFs.
    • Edit metadata and revision history.
  4. Cross-Platform Support:
    • Works with .NET Core (8, 7, 6, 5, and 3.1+), .NET Standard (2.0+), and .NET Framework (4.6.2+).
    • Compatible with Windows, Linux, and macOS.
    • Available on NuGet for easy installation.

Generate PDF documents Using IronPDF and DuckDB .NET

To start with, create a Console application using Visual Studio as below.

DuckDB C# (How It Works For Developers): Figure 3 - Console App

Provide the Project name.

DuckDB C# (How It Works For Developers): Figure 4 - Project Configuration

Provide .NET Version.

DuckDB C# (How It Works For Developers): Figure 5 - Target Framework

Install the IronPDF package.

DuckDB C# (How It Works For Developers): Figure 6 - IronPDF

Install the DuckDB.NET package.

DuckDB C# (How It Works For Developers): Figure 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

Code Explanation

The code aims to showcase how to use DuckDB.NET for database operations and IronPDF for generating a PDF report containing the database query results.

Key Components

  1. DuckDB.NET:

    • DuckDBConnection: Establishes a connection to an in-memory DuckDB database file ("Data Source=:memory:"). This connection is used throughout the code to execute SQL commands.
  2. Database Operations:

    • Table Creation: Defines a SQL command (CREATE TABLE integers(book STRING, cost INTEGER);) to create a table named integers with columns book (STRING) and cost (INTEGER).
    • Data Insertion: Inserts rows into the integers table (INSERT INTO integers VALUES ('book1', 25), ('book2', 30), ('book3', 10);).
    • Data Retrieval: Executes a SELECT query (SELECT book, cost FROM integers;) to fetch data from the integers table. The retrieved data is formatted into HTML (content) and printed to the console.
  3. PDF Generation with IronPDF:
    • Rendering HTML to PDF: Uses ChromePdfRenderer from IronPDF to convert the HTML content (content) into a PDF document (pdf).
    • Saving PDF: Saves the generated PDF as "AwesomeDuckDbNet.pdf" in the current directory.

Output

DuckDB C# (How It Works For Developers): Figure 8 - Console Output

PDF

DuckDB C# (How It Works For Developers): Figure 9 - PDF Output

IronPDF Licensing

The IronPDF package requires a license to run. Add the below code at the start of the application before the package is accessed.

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

A trial license is available on IronPDF's trial license page.

Conclusion

The DuckDB.NET C# package is a powerful tool for integrating DuckDB’s analytical capabilities into .NET applications. Its ease of use, support for various data formats, and seamless integration with C# make it an excellent choice for developers working on data-intensive applications. Whether you are building data analysis tools, ETL pipelines, or other data-driven applications, DuckDB.NET can help you achieve your goals efficiently.

자주 묻는 질문

C# 애플리케이션에서 DuckDB.NET은 어떤 용도로 사용되나요?

DuckDB.NET은 C# 애플리케이션 내에 DuckDB 네이티브 라이브러리를 통합하는 데 사용되며, ADO.NET 공급자를 통해 개발자에게 강력한 분석 기능을 제공합니다.

C# 프로젝트에 DuckDB.NET을 설치하려면 어떻게 해야 하나요?

DuckDB.NET은 .NET CLI 명령 dotnet add package DuckDB.NET.Data.Full를 사용하거나 Visual Studio의 NuGet 패키지 관리자를 통해 설치할 수 있습니다.

DuckDB.NET을 사용하여 SQL 쿼리를 실행하려면 어떻게 해야 하나요?

DuckDBConnection으로 연결을 설정하고 SQL 명령을 실행하여 테이블을 만들고, 데이터를 삽입하고, 검색하는 등 DuckDB.NET을 사용하여 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 파일로 내보낼 수 있습니다. 예를 들어, 테이블 데이터를 CSV 파일로 내보내려면 COPY integers TO 'output.csv'(FORMAT 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과 PDF 보고서 생성을 위한 IronPDF를 결합하여 DuckDB의 데이터베이스 기능과 IronPDF의 PDF 생성 기능을 활용할 수 있습니다.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.