Skip to footer content
.NET HELP

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)}");
        }
    }
}
Imports System
Imports DuckDB.NET.Data

Friend Class Program
	Shared Sub Main()
		' Create and open a connection to an in-memory DuckDB database
		Dim duckdbconnection As New DuckDBConnection("Data Source=:memory:")
		duckdbconnection.Open()

		' Create a command associated with the connection
		Dim 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
		Dim reader = command.ExecuteReader()
		Do While reader.Read()
			Console.WriteLine($"{reader.GetInt32(0)}, {reader.GetInt32(1)}")
		Loop
	End Sub
End Class
$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();
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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
}
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
$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();
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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");
    }
}
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
  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");
        }
    }
}
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
			Dim connection = New DuckDBConnection("Data Source=:memory:")
			connection.Open()
			Dim 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;"
			Dim reader = command.ExecuteReader()
			content &= "<p>SELECT book, cost FROM integers;</p>"

			' Execute the query and process the results, appending them to the HTML content
			Do While reader.Read()
				content &= $"<p>{reader.GetString(0)}, {reader.GetInt32(1)}</p>"
				Console.WriteLine($"{reader.GetString(0)}, {reader.GetInt32(1)}")
			Loop

			' 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
			Dim pdf = renderer.RenderHtmlAsPdf(content)
			pdf.SaveAs("AwesomeDuckDbNet.pdf")
		End Sub
	End Module
End Namespace
$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";
IRON VB CONVERTER ERROR developers@ironsoftware.com
$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.

Frequently Asked Questions

What is DuckDB.NET used for in C# applications?

DuckDB.NET is used to integrate the DuckDB native library within C# applications, providing developers with powerful analytical capabilities through an ADO.NET provider.

How can I install DuckDB.NET in a C# project?

You can install DuckDB.NET by using the .NET CLI command dotnet add package DuckDB.NET.Data.Full or through the NuGet Package Manager in Visual Studio.

How do I execute SQL queries using DuckDB.NET?

You can execute SQL queries using DuckDB.NET by establishing a connection with DuckDBConnection and executing SQL commands to create tables, insert, and retrieve data.

Can DuckDB.NET support reading data from CSV and Parquet files?

Yes, DuckDB.NET supports data ingestion from various formats, including CSV and Parquet files, allowing seamless integration and manipulation of these data types within C# applications.

How can I convert HTML to PDF in C#?

You can use IronPDF's RenderHtmlAsPdf method to convert HTML strings into PDFs. You can also convert HTML files into PDFs using RenderHtmlFileAsPdf.

What are the benefits of using DuckDB.NET for data-intensive projects?

DuckDB.NET offers powerful analytical capabilities, supports SQL-based data manipulation, and easily integrates with C# applications, making it ideal for data-intensive projects.

How can DuckDB.NET be integrated with data frames?

DuckDB.NET can integrate with data frames, enabling SQL-based data manipulation, which is particularly useful for performing complex data analysis tasks.

How do I export data to a CSV file using DuckDB.NET?

You can export data to a CSV file using DuckDB.NET with the COPY statement. For instance, use COPY integers TO 'output.csv' (FORMAT CSV); to export table data to a CSV file.

What platforms does IronPDF support?

IronPDF supports .NET Core (8, 7, 6, 5, and 3.1+), .NET Standard (2.0+), and .NET Framework (4.6.2+), and is compatible with Windows, Linux, and macOS.

Can I combine DuckDB.NET and IronPDF for generating reports?

Yes, you can combine DuckDB.NET for database operations and IronPDF for generating PDF reports, leveraging DuckDB's database capabilities with IronPDF's PDF generation features.

Chipego
Software Engineer
Chipego has a natural skill for listening that helps him to comprehend customer issues, and offer intelligent solutions. He joined the Iron Software team in 2023, after studying a Bachelor of Science in Information Technology. IronPDF and IronOCR are the two products Chipego has been focusing on, but his knowledge of ...Read More