.NET HELP

DuckDB C# (How It Works For Developers)

Published August 13, 2024
Share:

Introduction

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
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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()
    {
        using var duckdbconnection = new DuckDBConnection("Data Source=:memory:");
        duckdbconnection.Open();
        using var command = duckdbconnection.CreateCommand();
        command.CommandText = "CREATE TABLE integers(foo INTEGER, bar INTEGER);";
        command.ExecuteNonQuery();
        command.CommandText = "INSERT INTO integers VALUES (3, 4), (5, 6), (7, 8);";
        command.ExecuteNonQuery();
        command.CommandText = "Select count(*) from integers";
        var executeScalar = command.ExecuteScalar();
        command.CommandText = "SELECT foo, bar FROM integers;";
        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()
    {
        using var duckdbconnection = new DuckDBConnection("Data Source=:memory:");
        duckdbconnection.Open();
        using var command = duckdbconnection.CreateCommand();
        command.CommandText = "CREATE TABLE integers(foo INTEGER, bar INTEGER);";
        command.ExecuteNonQuery();
        command.CommandText = "INSERT INTO integers VALUES (3, 4), (5, 6), (7, 8);";
        command.ExecuteNonQuery();
        command.CommandText = "Select count(*) from integers";
        var executeScalar = command.ExecuteScalar();
        command.CommandText = "SELECT foo, bar FROM integers;";
        using var reader = command.ExecuteReader();
        while (reader.Read())
        {
            Console.WriteLine($"{reader.GetInt32(0)}, {reader.GetInt32(1)}");
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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();
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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)>();
while (reader.Read())
{
    results.Add((reader.GetInt32(0), reader.GetInt32(1))); 
    // can also use for with var index and iterate the results
}
var results = new List<(int foo, int bar)>();
while (reader.Read())
{
    results.Add((reader.GetInt32(0), reader.GetInt32(1))); 
    // can also use for with var index and iterate the results
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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();
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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:

  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;
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>";
            using var connection = new DuckDBConnection("Data Source=:memory:");
            connection.Open();
            using var command = connection.CreateCommand();
            command.CommandText = "CREATE TABLE integers(book STRING, cost INTEGER);";
            command.ExecuteNonQuery();
            content += "<p>CREATE TABLE integers(book STRING, cost INTEGER);</p>";
            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>";
            command.CommandText = "SELECT book, cost FROM integers;";
            using var reader = command.ExecuteReader();
            content += "<p>SELECT book, cost FROM integers;</p>";
            while (reader.Read())
            {
                content += $"<p>{reader.GetString(0)}, {reader.GetInt32(1)}</p>";
                Console.WriteLine($"{reader.GetString(0)}, {reader.GetInt32(1)}");
            }
            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();
            var pdf = renderer.RenderHtmlAsPdf(content);
            // Export to a file or Stream
            pdf.SaveAs("AwesomeDuckDbNet.pdf");
        }
    }
}
using DuckDB.NET.Data;
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>";
            using var connection = new DuckDBConnection("Data Source=:memory:");
            connection.Open();
            using var command = connection.CreateCommand();
            command.CommandText = "CREATE TABLE integers(book STRING, cost INTEGER);";
            command.ExecuteNonQuery();
            content += "<p>CREATE TABLE integers(book STRING, cost INTEGER);</p>";
            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>";
            command.CommandText = "SELECT book, cost FROM integers;";
            using var reader = command.ExecuteReader();
            content += "<p>SELECT book, cost FROM integers;</p>";
            while (reader.Read())
            {
                content += $"<p>{reader.GetString(0)}, {reader.GetInt32(1)}</p>";
                Console.WriteLine($"{reader.GetString(0)}, {reader.GetInt32(1)}");
            }
            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();
            var pdf = renderer.RenderHtmlAsPdf(content);
            // Export to a file or Stream
            pdf.SaveAs("AwesomeDuckDbNet.pdf");
        }
    }
}
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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 var column 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. The print-to-console functionality can also be moved to a new private static void printqueryresults method.
  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";
IRON VB CONVERTER ERROR developers@ironsoftware.com
VB   C#

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.

< PREVIOUS
LazyCache C# (How It Works For Developers)
NEXT >
WebGrease .NET Core (How It Works For Developers)

Ready to get started? Version: 2024.12 just released

Free NuGet Download Total downloads: 11,622,374 View Licenses >