Performing DB2 operations in C#

Photo by Tom Podmore on Unsplash

Performing DB2 operations in C#

IBM Db2 is a powerful relational database management system known for its scalability, performance, and reliability. If you're developing a C# application and need to interact with a Db2 database, this article will guide you through the essential steps for performing Db2 operations using C#.

Prerequisites

Before you start working with Db2 in your C# application, make sure you have the following prerequisites in place:

  1. IBM Db2 Database: You should have access to an IBM Db2 database server. Ensure you have the necessary credentials (username and password) and connection details (host and port) to connect to the database.

  2. IBM Data Server Client: You need to install the IBM Data Server Client on the machine where your C# application will run. This client provides the necessary libraries and tools for connecting to Db2 databases.

  3. Visual Studio or Visual Studio Code: You can use Visual Studio or Visual Studio Code as your integrated development environment (IDE) for C# development.

  4. Db2 .NET Data Provider: Install the IBM.Data.DB2.Core NuGet package in your C# project. This package contains the Db2 .NET Data Provider, which allows you to interact with Db2 databases from your C# code.

Step 1: Create a C# Project

Start by creating a new C# project in your preferred IDE. You can choose a console application, a Windows Forms application, or any other C# project type that suits your needs.

Step 2: Configure Connection String

To connect to your Db2 database, you'll need to specify a connection string that includes the necessary connection details. Here's an example of a Db2 connection string:

string connectionString = "Server=myserver;Database=mydb;User=myuser;Password=mypassword;";

Replace myserver, mydb, myuser, and mypassword with your actual database server details.

Step 3: Establish a Db2 Connection

In your C# code, you can use the DbConnection class from the Db2 .NET Data Provider to establish a connection to the database. Here's how you can do it:

using IBM.Data.DB2.Core;

// ...

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

    // Perform Db2 operations here...

    connection.Close();
}

Wrap the connection in a using block to ensure that it is properly opened and closed, even if an exception occurs during the operation.

Step 4: Execute SQL Queries

Now that you have a connection to the Db2 database, you can execute SQL queries using the DbCommand and DbDataReader classes. Here's an example of executing a SELECT query:

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

    using (DbCommand command = connection.CreateCommand())
    {
        command.CommandText = "SELECT * FROM mytable";

        using (DbDataReader reader = command.ExecuteReader())
        {
            while (reader.Read())
            {
                // Map data to a C# class (e.g., MyClass)
                MyClass myObject = new MyClass
                {
                    Property1 = reader["Column1"].ToString(),
                    Property2 = Convert.ToInt32(reader["Column2"]),
                    // Map other properties as needed
                };

                // Access and process myObject here...
            }
        }
    }

    connection.Close();
}

Replace "SELECT * FROM mytable" with your SQL query.

Step 5: Perform Other Db2 Operations

Db2 supports various SQL operations, including INSERT, UPDATE, DELETE, and stored procedure calls. You can use the DbCommand class to execute these operations. Here's an example of inserting data into a table:

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

    using (DbCommand command = connection.CreateCommand())
    {
        command.CommandText = "INSERT INTO mytable (column1, column2) VALUES (@value1, @value2)";

        // Add parameters to the command
        command.Parameters.Add(new DB2Parameter("@value1", "some value"));
        command.Parameters.Add(new DB2Parameter("@value2", 42));

        int rowsAffected = command.ExecuteNonQuery();

        // Check rowsAffected for the number of rows inserted
    }

    connection.Close();
}

Step 6: Error Handling

It's essential to implement error handling when working with databases. Handle exceptions that may occur during database operations gracefully. You can catch and handle Db2-specific exceptions to provide meaningful error messages to users.

try
{
    // Db2 operations here...
}
catch (DB2Exception ex)
{
    // Handle Db2-specific exceptions
    Console.WriteLine($"Db2 Error: {ex.Message}");
}
catch (Exception ex)
{
    // Handle other exceptions
    Console.WriteLine($"Error: {ex.Message}");
}

Step 7: Clean Up

Always close the Db2 connection when you're done with it to release resources. You can do this using a finally block or by using the using block, as shown in the earlier examples.

Calling Stored Procedure in DB2

To execute a stored procedure in Db2 from your C# application, follow these steps:

Define the Stored Procedure

First, ensure that you have a stored procedure defined in your Db2 database. Here's an example of a simple stored procedure that retrieves data from a table:

CREATE OR REPLACE PROCEDURE GetEmployeeWithException(
    IN employeeId INT,
    OUT success INT,
    OUT errorCode INT,
    OUT errorMessage VARCHAR(255)
)
BEGIN
--### ERROR HANDLER ######################
    DECLARE EXIT HANDLER FOR SQLEXCEPTION
    BEGIN
        SET success = 0;
        GET DIAGNOSTICS CONDITION 1
            errorCode = DB2_RETURNED_SQLCODE,
            errorMessage = DB2_MESSAGE_TEXT;
    END;

    DECLARE EXIT HANDLER FOR NOT FOUND
    BEGIN
        SET success = 0;
        SET errorCode = -1;
        SET errorMessage = 'Employee not found.';
    END;

--### DATA FETCH ######################
    DECLARE cursor1 CURSOR FOR
        SELECT * FROM Employee WHERE EmployeeID = employeeId;

    SET success = 1;
    SET errorCode = 0;
    SET errorMessage = '';

    OPEN cursor1;
END

In this stored procedure:

  • We declare output parameters success, errorCode, and errorMessage to indicate the success or failure of the operation and to provide error details in case of an error.

  • We use DECLARE EXIT HANDLER to define exception handlers for SQLEXCEPTION (for general database errors) and NOT FOUND (for when no records are found).

  • Inside the handlers, we set the success flag to 0 to indicate failure, and we retrieve the error code and message using GET DIAGNOSTICS.

  • If no exceptions are raised, we set success to 1 to indicate success and clear the error details.

Call the Stored Procedure

Now, you can call this stored procedure from your C# code:

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

    using (DbCommand command = connection.CreateCommand())
    {
        command.CommandText = "GetEmployeeWithException";
        command.CommandType = CommandType.StoredProcedure;

        // Add parameters to the command
        DbParameter employeeIdParameter = command.CreateParameter();
        employeeIdParameter.ParameterName = "@employeeId";
        employeeIdParameter.Value = 1; // Replace with the desired employee ID
        command.Parameters.Add(employeeIdParameter);

        DbParameter successParameter = command.CreateParameter();
        successParameter.ParameterName = "@success";
        successParameter.Direction = ParameterDirection.Output;
        successParameter.DbType = DbType.Int32;
        command.Parameters.Add(successParameter);

        DbParameter errorCodeParameter = command.CreateParameter();
        errorCodeParameter.ParameterName = "@errorCode";
        errorCodeParameter.Direction = ParameterDirection.Output;
        errorCodeParameter.DbType = DbType.Int32;
        command.Parameters.Add(errorCodeParameter);

        DbParameter errorMessageParameter = command.CreateParameter();
        errorMessageParameter.ParameterName = "@errorMessage";
        errorMessageParameter.Direction = ParameterDirection.Output;
        errorMessageParameter.DbType = DbType.String;
        errorMessageParameter.Size = 255; // Adjust the size as needed
        command.Parameters.Add(errorMessageParameter);

        try
        {
            command.ExecuteNonQuery();

            int success = Convert.ToInt32(successParameter.Value);
            int errorCode = Convert.ToInt32(errorCodeParameter.Value);
            string errorMessage = errorMessageParameter.Value.ToString();

            if (success == 1)
            {
                // The stored procedure executed successfully
                // Handle the results, if any
            }
            else
            {
                // An error occurred
                Console.WriteLine($"Error Code: {errorCode}");
                Console.WriteLine($"Error Message: {errorMessage}");
            }
        }
        catch (DB2Exception ex)
        {
            // Handle Db2-specific exceptions here
            Console.WriteLine($"Db2 Error: {ex.Message}");
        }
    }

    connection.Close();
}

Ensure that you have a C# class (Employee) to map the stored procedure results.

Conclusion

Interacting with an IBM Db2 database from a C# application is achievable by following these steps. Make sure you have the required prerequisites in place, configure the connection string, establish a connection, execute SQL queries, handle errors, and clean up resources. Whether you're building a desktop application, a web application, or a service, these fundamental steps will help you integrate Db2 operations seamlessly into your C# application.