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. The example driver this blog uses is the Easysoft ODBC-JDBC Gateway, which translates between ODBC and JDBC, enabling you to work with Java data from .NET.
- If you haven't done so already, install .NET as per Microsoft's instructions.
- Make sure your .NET machine's library path includes the
unixODBC/lib
directory. If you're using the unixODBC Driver Manager that's included in an Easysoft driver distribution, you will also need to add a symbolic link forlibodbc.so.2
. For example:cd /usr/local/easysoft/unixODBC/lib ln -s libodbc.so.1 libodbc.so.2
- Next, install the ODBC part of .NET:
dotnet add package System.Data.Odbc --version 4.7.0
- Create a new .NET program. For example:
dotnet new console --output sample1
- 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 theodbc.ini
file. - To run the sample:
dotnet run --project sample1