Namespace: System.Data.OdbcClient
Assembly: System.Data.dll
Description: Provides access to data sources through ODBC (Open Database Connectivity) by using managed code. The OdbcClient classes enable you to connect to an ODBC data source, execute commands, and retrieve results.
The System.Data.OdbcClient
namespace contains classes that allow your .NET applications to interact with data sources using the ODBC standard. This is particularly useful when you need to connect to legacy databases or systems that provide an ODBC driver but do not have a native .NET data provider.
The primary classes in this namespace mirror those found in System.Data.SqlClient
and System.Data.OleDbClient
, providing a familiar interface for database operations.
The System.Data.OdbcClient
namespace provides a set of core classes for interacting with ODBC data sources:
OdbcCommand
and its mapping to and from the DataSet in the .NET Framework.To connect to an ODBC data source, you typically use the OdbcConnection
class. You'll need to specify a connection string that includes the Data Source Name (DSN) or the full driver path and connection details.
Using a DSN named "MyOdbcDataSource":
string connectionString = "DSN=MyOdbcDataSource;Uid=myUser;Pwd=myPassword;";
Using a driver path:
string connectionString = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\mydatabase.accdb;Uid=admin;Pwd=;";
using System;
using System.Data;
using System.Data.Odbc;
public class OdbcExample
{
public static void Main(string[] args)
{
string connectionString = "DSN=MyOdbcDataSource;Uid=myUser;Pwd=myPassword;";
using (OdbcConnection connection = new OdbcConnection(connectionString))
{
try
{
connection.Open();
Console.WriteLine("Connection opened successfully.");
// Example of executing a command
string query = "SELECT COUNT(*) FROM MyTable";
using (OdbcCommand command = new OdbcCommand(query, connection))
{
object result = command.ExecuteScalar();
Console.WriteLine($"Row count: {result}");
}
}
catch (OdbcException ex)
{
Console.WriteLine($"Error: {ex.Message}");
foreach (OdbcError error in ex.Errors)
{
Console.WriteLine($"- {error.Message} (SQLState: {error.SQLState}, NativeError: {error.NativeError})");
}
}
catch (Exception ex)
{
Console.WriteLine($"An unexpected error occurred: {ex.Message}");
}
}
}
}