Getting Started With dotConnect for Db2

Below are some resources to help you maximize your experience with dotConnect for Db2.

dotConnect for Db2 is a high-performance ADO.NET data provider with ORM support, providing fast, encrypted access to IBM Db2 databases for application development.

  • EF Core, Dapper, NHibernate, LinqConnect, and other ORMs support
  • SSL, SSH, proxy servers, and HTTP tunnels support
  • Broad compatibility with various .NET platforms and versions
  • Full compliance with ADO.NET
  • Integration with Visual Studio
dotConnect for Db2 requires a Db2 server client installed on the machine to establish a connection to the database. For instructions, refer to the installation guide.

Code examples

using Devart.Data.DB2;

namespace DB2ConnectionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "" +
                "User Id=TestUser;" +
                "Password=TestPassword;" +
                "Server=127.0.0.1;" +
                "Database=TestDatabase;" +
                "current schema=TestSchema;" +
                "License Key=**********";

            using (DB2Connection connection = new DB2Connection(connectionString))
            {
                try
                {
                    connection.Open();
                    Console.WriteLine("Connection successful!");
                }
                catch (DB2Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }
            }
        }
    }
}
PM> Install-Package Devart.Data.DB2
using Devart.Data.DB2;

namespace DB2ConnectionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "" +
            "Server=127.0.0.1;" +
            "User Id=TestUser;" +
            "Password=TestPassword;" +
            "Database=TestDB;" +
            "current schema=TestSchema;" +
            "Security=SSL;" +
            "SSLClientKeystash=path/to/your/keystash.sth;" +
            "SSLClientKeystoredb=path/to/your/keystore.kdb;" +
            "License Key=**********";

            using (DB2Connection connection = new DB2Connection(connectionString))
            {
                try
                {
                    connection.Open();
                    Console.WriteLine("Connection successful!");
                }
                catch (DB2Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }
            }
        }
    }
}
PM> Install-Package Devart.Data.DB2
using Devart.Data.DB2;

namespace DB2ConnectionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "" +
                "User Id=TestUser;" +
                "Password=TestPassword;" +
                "Server=127.0.0.1;" +
                "Database=TestDatabase;" +
                "current schema=TestSchema;" +
                "License Key=**********";

            using (DB2Connection connection = new DB2Connection(connectionString))
            {
                try
                {
                    connection.Open();
                    Console.WriteLine("Connection successful!");

                    string query = "SELECT CUSTOMERID, FIRSTNAME, LASTNAME, EMAIL, PHONE, COMPANY FROM CUSTOMERS";
                    using (DB2Command command = new DB2Command(query, connection))
                    {
                        using (DB2DataReader reader = command.ExecuteReader())
                        {
                            Console.WriteLine("\n--- Contact Information ---");
                            while (reader.Read())
                            {
                                string customerId = reader.IsDBNull(reader.GetOrdinal("CUSTOMERID")) ? "N/A" : reader["CUSTOMERID"].ToString();
                                string firstName = reader.IsDBNull(reader.GetOrdinal("FIRSTNAME")) ? "N/A" : reader["FIRSTNAME"].ToString();
                                string lastName = reader.IsDBNull(reader.GetOrdinal("LASTNAME")) ? "N/A" : reader["LASTNAME"].ToString();
                                string email = reader.IsDBNull(reader.GetOrdinal("EMAIL")) ? "N/A" : reader["EMAIL"].ToString();
                                string phone = reader.IsDBNull(reader.GetOrdinal("PHONE")) ? "N/A" : reader["PHONE"].ToString();
                                string company = reader.IsDBNull(reader.GetOrdinal("COMPANY")) ? "N/A" : reader["COMPANY"].ToString();

                                Console.WriteLine($"CUSTOMERID: {customerId}, FIRSTNAME: {firstName}, LASTNAME: {lastName}, EMAIL: {email}, PHONE: {phone}, COMPANY: {company}");
                            }
                        }
                    }
                }
                catch (DB2Exception ex)
                {
                    Console.WriteLine($"Error: {ex.Message}");
                }
            }
        }
    }
}
PM> Install-Package Devart.Data.DB2
using System;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using Devart.Data.DB2.EFCore;

public class Customer
{
    public int CUSTOMERID { get; set; }
    public string FIRSTNAME { get; set; }
    public string LASTNAME { get; set; }
    public string EMAIL { get; set; }
    public string PHONE { get; set; }
    public string COMPANY { get; set; }
}

public class CustomerContext : DbContext
{
    private readonly string _connectionString;

    public CustomerContext(string connectionString)
    {
        _connectionString = connectionString;
    }

    public DbSet Customers { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
            optionsBuilder.UseDb2(_connectionString);
        }
    }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity(entity =>
        {
            entity.ToTable("CUSTOMERS"); 
            entity.HasKey(e => e.CUSTOMERID);
        });
    }
}

namespace DB2ConnectionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "" +
                "User Id=TestUser;" +
                "Password=TestPassword;" +
                "Server=127.0.0.1;" +
                "Database=TestDatabase;" +
                "current schema=TestSchema;" +
                "License Key=**********";
            try
            {
                using (var context = new CustomerContext(connectionString))
                {
                    context.Database.EnsureCreated();
                    Console.WriteLine("Connection successful!");

                    Console.WriteLine("\n--- Contact Information ---");
                    var allCustomers = context.Customers.ToList();
                    
                    if (allCustomers.Any())
                    {
                        foreach (var c in allCustomers)
                        {
                            Console.WriteLine($"ID: {c.CUSTOMERID}, Name: {c.FIRSTNAME} {c.LASTNAME}, " +
                                              $"Email: {c.EMAIL}, Phone: {c.PHONE}, Company: {c.COMPANY}");
                        }
                    }
                    else
                    {
                        Console.WriteLine("No customers found in the database.");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An error occurred: {ex.Message}");
                if (ex.InnerException != null)
                {
                    Console.WriteLine($"Inner Exception: {ex.InnerException.Message}");
                }
            }
        }
    }
}
PM> Install-Package Devart.Data.DB2.EFCore
using Devart.Data.DB2;
using System.Data;

namespace DB2ConnectionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "" +
                "User Id=TestUser;" +
                "Password=TestPassword;" +
                "Server=127.0.0.1;" +
                "Database=TestDatabase;" +
                "current schema=TestSchema;" +
                "License Key=**********";
            try
            {
                Console.WriteLine("--- Contact Information ---");

                string query = "SELECT CUSTOMERID, FIRSTNAME, LASTNAME, EMAIL, PHONE, COMPANY FROM CUSTOMERS";

                using (DB2Connection connection = new DB2Connection(connectionString))
                {
                    DB2DataAdapter dataAdapter = new DB2DataAdapter(query, connection);

                    DataSet dataSet = new DataSet();

                    dataAdapter.Fill(dataSet, "Customers");

                    if (dataSet.Tables.Contains("Customers") && dataSet.Tables["Customers"].Rows.Count > 0)
                    {
                        DataTable customersTable = dataSet.Tables["Customers"];

                        foreach (DataRow row in customersTable.Rows)
                        {
                            Console.WriteLine($"ID: {row["CUSTOMERID"]}, Name: {row["FIRSTNAME"]} {row["LASTNAME"]}, " +
                                              $"Email: {row["EMAIL"]}, Phone: {row["PHONE"]}, Company: {row["COMPANY"]}");
                        }
                    }
                    else
                    {
                        Console.WriteLine("No customers found in the database.");
                    }
                }
            }
            catch (DB2Exception ex)
            {
                Console.WriteLine($"A DB2 error occurred: {ex.Message}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"An unexpected error occurred: {ex.Message}");
            }
        }
    }
}
PM > Install-Package Devart.Data.DB2
using Devart.Data.DB2;

namespace DB2ConnectionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "" +
                "User Id=TestUser;" +
                "Password=TestPassword;" +
                "Server=127.0.0.1;" +
                "Database=TestDatabase;" +
                "current schema=TestSchema;" +
                "License Key=**********";

            using (DB2Connection connection = new DB2Connection(connectionString))
            {
                DB2Transaction transaction = null;
                try
                {
                    connection.Open();
                    Console.WriteLine("Connection successful!");

                    transaction = connection.BeginTransaction();
                    Console.WriteLine("Transaction started.");

                    string insertQuery = "INSERT INTO CUSTOMERS (CUSTOMERID, FIRSTNAME, LASTNAME, EMAIL, PHONE, COMPANY) " +
                                         "VALUES (@ID, @FirstName, @LastName, @Email, @Phone, @Company)";

                    using (DB2Command command = new DB2Command(insertQuery, connection, transaction))
                    {
                        command.Parameters.Add("@ID", DB2Type.Integer).Value = 101;
                        command.Parameters.Add("@FirstName", DB2Type.VarChar).Value = "Jane";
                        command.Parameters.Add("@LastName", DB2Type.VarChar).Value = "Smith";
                        command.Parameters.Add("@Email", DB2Type.VarChar).Value = "[email protected]";
                        command.Parameters.Add("@Phone", DB2Type.VarChar).Value = "555-9876";
                        command.Parameters.Add("@Company", DB2Type.VarChar).Value = "Transactional Corp";

                        int rowsAffected = command.ExecuteNonQuery();
                        Console.WriteLine($"{rowsAffected} new row inserted.");
                    }

                    transaction.Commit();
                    Console.WriteLine("Transaction committed successfully.");
                }
                catch (DB2Exception ex)
                {
                    Console.WriteLine($"A DB2 error occurred: {ex.Message}");
                    try
                    {
                        transaction?.Rollback();
                        Console.WriteLine("Transaction rolled back.");
                    }
                    catch (Exception rbEx)
                    {
                        Console.WriteLine($"An error occurred during transaction rollback: {rbEx.Message}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"An unexpected error occurred: {ex.Message}");
                    try
                    {
                        transaction?.Rollback();
                        Console.WriteLine("Transaction rolled back.");
                    }
                    catch (Exception rbEx)
                    {
                        Console.WriteLine($"An error occurred during transaction rollback: {rbEx.Message}");
                    }
                }
            }
        }
    }
}
PM> Install-Package Devart.Data.DB2
using Devart.Data.DB2;

namespace DB2ConnectionExample
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "" +
                "User Id=TestUser;" +
                "Password=TestPassword;" +
                "Server=127.0.0.1;" +
                "Database=TestDatabase;" +
                "current schema=TestSchema;" +
                "License Key=**********";

            try
            {
                using (DB2Connection connection = new DB2Connection(connectionString))
                {
                    connection.Open();

                    DB2DataTable dataTable = new DB2DataTable();
                    dataTable.SelectCommand = new DB2Command(
                        "SELECT CUSTOMERID, FIRSTNAME, LASTNAME, EMAIL, PHONE, COMPANY FROM CUSTOMERS WHERE 1=0",
                        connection);
                    dataTable.Open();

                    dataTable.Rows.Add(new object[] { 301, "Alice", "Johnson", "[email protected]", "555-0101", "Company A" });
                    dataTable.Rows.Add(new object[] { 302, "Bob", "Williams", "[email protected]", "555-0102", "Company B" });
                    dataTable.Rows.Add(new object[] { 303, "Carol", "Dawson", "[email protected]", "555-0103", "Company C" });

                    dataTable.UpdateBatchSize = 100;

                    int affected = dataTable.Update();
                    Console.WriteLine($"{affected} rows inserted/updated.");
                }
            }
            catch (DB2Exception ex)
            {
                Console.WriteLine("A DB2 error occurred: " + ex.Message);
            }
            catch (Exception ex)
            {
                Console.WriteLine("An error occurred: " + ex.Message);
            }
        }
    }
}
PM> Install-Package Devart.Data.DB2

How-to articles

Connect to Db2 in .NET Applications
Learn how to establish a connection to Db2 in .NET applications, which can further be opened, closed, and modified.
Using Entity Framework Core With Db2
Find out how to connect Db2 to your application using EF Core and ADO.NET.
Db2 Connection Strings
Explore the parameters that are necessary to establish successful connections to Db2 databases.

Documentation

Licensing
Licensing
A detailed technical reference on embedding license information for apps built with dotConnect for Db2.
DataAdapter Features
DataAdapter features
A guide to using the DB2DataAdapter class for interacting with Db2 data in a disconnected architecture.
Parameters
Parameters
An overview of SQL query parameters and their synchronization, along with practical insights into working with stored procedures.
Batch data insertion
Batch data insertion
A guideline on batch data insertion and update using DB2Command with practical examples.

dotConnect Universal

Get universal access to data from a variety of sources, including SQL Server, Oracle, PostgreSQL, MySQL, SQLite, DB2, InterBase, Microsoft Access, and Firebird. Other servers can be accessed through their ADO.NET, OLE DB and ODBC providers.

FAQ

What is the trial period for dotConnect for Db2?
dotConnect for Db2 offers a fully functional 30-day trial. During this period, you can use and evaluate all features without limitations. After the trial ends, you can purchase a license to keep using the product.
Why do I need to install the product if NuGet is available?

dotConnect for Db2 provides two sets of assemblies, and the choice depends on your project type:

  • For .NET Framework projects: Use the Devart assemblies included with the product installer.
  • For .NET (.NET Core/.NET 5+) projects: Use the assemblies available via NuGet packages.
Where should I apply my License Key?

The method for applying your license depends on your project type:

  • For .NET (.NET Core/.NET 5+) projects, apply the License Key at runtime using the License Key connection string parameter.
  • For .NET Framework projects, no license key is necessary. Download and install the licensed version of dotConnect from your Devart Customer Portal.
Do the end-users of my application need a Devart license, or do I have to pay additional fees for deploying my software?

No, end users do not need a Devart license, and there are no additional deployment fees, as long as you hold a valid Devart license.

According to the EULA, you're allowed to redistribute the following runtime assemblies with your application:

  • Devart.Data.DB2.dll
  • Devart.Data.dll

You can include them in your app's folder (such as Bin for web apps) or register them in the GAC. Just make sure to use them in your solution only.

There's no need for a full installation on the target machine, you can also use the "Minimal installation" option provided by the setup. It does not disturb any other dotConnect components.

How can I update dotConnect to a new version?

To update dotConnect to a new version, you need to reinstall it:

  • 1. Open Settings > Apps > Installed apps in Windows.
  • 2. Uninstall the current and any older versions of dotConnect, including Entity Developer and LinqConnect, if installed.
  • 3. Visit the Customer Portal and download the latest licensed version.
  • 4. Install the downloaded version and receive the latest features and improvements.
How can I completely remove all previous versions of a product?

1. Go to Settings > Apps > Installed apps and uninstall:

  • All dotConnect providers
  • Entity Developer
  • LinqConnect

2. Manually delete any leftover files from the following locations (if they exist):

GAC folders:

  • C:\Windows\assembly\GAC_MSIL
  • C:\Windows\Microsoft.NET\assembly\GAC_MSIL

Program files and extensions:

  • C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\Common7\IDE\Extensions\Devart
  • C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\Extensions\Devart
  • C:\Program Files (x86)\Devart
  • C:\Program Files\Devart
  • C:\Program Files (x86)\Common Files\Devart
  • C:\Program Files\Common Files\Devart

Program data folders:

  • C:\ProgramData\Devart\dotConnect
  • C:\ProgramData\Devart\Entity Developer

Removing these ensures a clean system and prevents conflicts during future installations.

Wield the full firepower of dotConnect for Db2
Go with the advanced edition of dotConnect for Db2 and stay at the top of your game from day one!