
DuckDB en C# | Base de datos analítica embebida for .NET
DuckDB.NET es un proveedor de código abierto de enlaces .NET para la biblioteca nativa de DuckDB, diseñado para integrarse perfectamente con C#. Proporciona un proveedor ADO.NET, lo que facilita el uso de DuckDB, una biblioteca de enlaces de bajo nivel, dentro de aplicaciones .NET. Este paquete es ideal para desarrolladores que buscan aprovechar las potentes capacidades analíticas de DuckDB en un entorno C#.
Instalación
Instalar DuckDB.NET es sencillo. Puedes agregarlo a tu proyecto usando el CLI de .NET:
dotnet add package DuckDB.NET.Data.Full
Alternativamente, puedes instalarlo a través del Administrador de Paquetes NuGet en Visual Studio.
Uso básico
Una vez instalado, puedes comenzar a usar DuckDB.NET para ejecutar consultas SQL dentro de tu aplicación C#. Aquí tienes un ejemplo simple:
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 ModuleEste ejemplo demuestra cómo crear una tabla, insertar datos y consultar los datos usando DuckDB.NET.
Resultado

Ingesta de datos
DuckDB.NET soporta la lectura de datos desde varios formatos, incluidos archivos CSV y Parquet. Aquí tienes cómo puedes leer datos de un archivo CSV:
command.CommandText = "COPY integers FROM 'example.csv' (FORMAT CSV);";
command.ExecuteNonQuery();command.CommandText = "COPY integers FROM 'example.csv' (FORMAT CSV)"
command.ExecuteNonQuery()Integración con DataFrames
DuckDB.NET también puede integrarse con marcos de datos, permitiéndote manipular datos usando una sintaxis SQL familiar. Esto es particularmente útil para tareas de análisis de datos.
Conversión de resultados
Puedes convertir los resultados de las consultas a varios formatos, como listas u objetos personalizados, facilitando el trabajo con los datos en tu aplicación:
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
LoopEscribir datos en disco
DuckDB.NET soporta escribir datos en disco en varios formatos. Puedes usar la instrucción COPY para exportar datos a un archivo CSV:
command.CommandText = "COPY integers TO 'output.csv' (FORMAT CSV);";
command.ExecuteNonQuery();command.CommandText = "COPY integers TO 'output.csv' (FORMAT CSV)"
command.ExecuteNonQuery()Introducción a IronPDF

IronPDF es una biblioteca PDF para C# que permite la generación, manejo y extracción de contenido de documentos PDF en proyectos .NET. Aquí algunas características clave:
IronPDF es una herramienta útil que te permite convertir páginas web, URLs y HTML a PDF. ¿La mejor parte? Los PDFs se ven exactamente como las páginas web originales, manteniendo toda la configuración y estilo. Entonces, si necesitas hacer un PDF de algo en línea, como un informe o una factura, IronPDF es tu opción.
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-
Conversión de HTML a PDF:
- Convierte contenido HTML, CSS y JavaScript a PDFs.
- Motor de Renderizado de Chrome para documentos PDF con precisión de píxeles.
- Genera PDFs desde URLs, archivos HTML o cadenas HTML.
-
Conversión de imágenes y contenidos:
- Convierte imágenes hacia y desde documentos PDF.
- Extrae texto e imágenes de documentos PDF existentes.
- Soporte para varios formatos de imagen como JPG, PNG, etc.
-
Edición y manipulación:
- Establece propiedades, seguridad y permisos para documentos PDF.
- Añade firmas digitales a PDFs.
- Edita metadatos e historial de revisiones.
-
Compatibilidad multiplataforma:
- Funciona con .NET Core (8, 7, 6, 5 y 3.1+), .NET Standard (2.0+) y .NET Framework (4.6.2+).
- Compatible con Windows, Linux y macOS.
- Disponible en NuGet para una fácil instalación.
Generar documentos PDF con IronPDF y DuckDB .NET
Para comenzar, crea una aplicación de consola usando Visual Studio como se muestra a continuación.

Proporciona el nombre del Proyecto.

Proporcione la Versión .NET.

Instala el paquete IronPDF.

Instala el paquete 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 NamespaceExplicación del código
El objetivo del código es mostrar cómo usar DuckDB.NET para operaciones de base de datos e IronPDF para generar un informe en PDF que contenga los resultados de las consultas a la base de datos.
Componentes clave
-
DuckDB .NET:
- DuckDBConnection: establece una conexión a un archivo de base de datos DuckDB en memoria ("Data Source=:memory:"). Esta conexión se utiliza a lo largo del código para ejecutar comandos SQL.
-
Operaciones de base de datos:
- Creación de tabla: define un comando SQL (CREATE TABLE integers(book STRING, cost INTEGER);) para crear una tabla llamada integers con columnas book (STRING) y cost (INTEGER).
- Inserción de datos: inserta filas en la tabla de enteros (INSERT INTO integers VALUES ('book1', 25), ('book2', 30), ('book3', 10);).
- Recuperación de datos: ejecuta una consulta SELECT (SELECT book, cost FROM integers;) para obtener datos de la tabla de enteros. Los datos recuperados se formatean en HTML (content) y se imprimen en la consola.
-
Generación de PDF con IronPDF:
- Representación de HTML a PDF: utiliza ChromePdfRenderer de IronPDF para convertir el contenido HTML (contenido) en un documento PDF (pdf).
- Guardar PDF: guarda el PDF generado como "AwesomeDuckDbNet.pdf" en el directorio actual.
Resultado


Licencias de IronPDF
El paquete IronPDF requiere una licencia para ejecutar. Agrega el siguiente código al inicio de la aplicación antes de que se acceda al paquete.
IronPdf.License.LicenseKey = "IRONPDF-KEY";Imports IronPdf
IronPdf.License.LicenseKey = "IRONPDF-KEY"Una licencia de prueba está disponible en la página de licencia de prueba de IronPDF.
Conclusión
El paquete DuckDB.NET C# es una herramienta poderosa para integrar las capacidades analíticas de DuckDB en aplicaciones .NET. Su facilidad de uso, soporte para varios formatos de datos e integración perfecta con C# lo hacen una excelente opción para desarrolladores que trabajan en aplicaciones intensivas de datos. Ya sea que estés construyendo herramientas de análisis de datos, canalizaciones ETL u otras aplicaciones impulsadas por datos, DuckDB.NET puede ayudarte a lograr tus objetivos de manera eficiente.

Jacob Mellor es Director de Tecnología de Iron Software y un ingeniero visionario pionero en la tecnología C# PDF. Como desarrollador original de la base de código principal de Iron Software, ha dado forma a la arquitectura de productos de la empresa desde su creación, transformándola, junto con el director ejecutivo Cameron Rimington, en una empresa de más de 50 personas que presta servicios a la NASA, Tesla y organismos gubernamentales de todo el mundo.
Artículos Relacionados


