Connecting .NET on Linux to an ODBC Data Source

This blog describes how to get an ODBC connection from .NET on Linux. You can use .NET with any Easysoft ODBC driver that's available on the Linux platform. This example driver this blog uses is the Easysoft ODBC-JDBC Gateway, which converts between ODBC and JDBC, enabling you to work with Java data from .NET.

  1. If you haven't done so already, install .NET as per Microsoft's instructions.
  2. Make sure your .NET machine's library path includes the unixODBC/lib folder. If you are using the unixODBC Driver Manager that's included in an Easysoft driver distribution, you will also need to add a symbolic link for libodbc.so.2. For example:
    cd /usr/local/easysoft/unixODBC/lib
    ln -s libodbc.so.1 libodbc.so.2
  3. Next, install the ODBC part of .NET:
    dotnet add package System.Data.Odbc --version 4.7.0
  4. Create a new .NET program. For example:
    dotnet new console --output sample1
  5. Edit Program.cs, and use something like:
    using System;
    using System.Data.Odbc;
    
    namespace EasysoftODBCJDBCSample
    {
        class Program
        {
            static void Main(string[] args)
            {
                try
                {
                    OdbcConnection DbConnection = new OdbcConnection("DSN=OJG");
                    DbConnection.Open();
                    OdbcCommand DbCommand = DbConnection.CreateCommand();
    
                    DbCommand.CommandText = "select * from MyTable";
                    OdbcDataReader DbReader = DbCommand.ExecuteReader();
    
                    while( DbReader.Read())
                    {
                        for (int i = 0; i < DbReader.FieldCount; i++)
                        {
                            if (DbReader.IsDBNull(i))
                            {
                            Console.Write("NULL,");
                            }
                            else
                            {
     Console.Write(DbReader.GetValue(i).ToString() + ",");
                            }
                        }
                        Console.WriteLine();
                    }
    
                    Console.Write("Data Finished");
                    DbReader.Close();
                    DbCommand.Dispose();
                    DbConnection.Close();
                }
                catch (OdbcException ex)
                {
                    Console.WriteLine(ex.Message);
                    return;
                }
            }
        }
    }

    In the line:

    OdbcConnection DbConnection = new OdbcConnection("DSN=OJG");

    Replace OJG with the name of your ODBC data source as defined in the odbc.ini file.

  6. To run the sample:
    dotnet run --project sample1