MSDN Documentation

System.Data.Odbc Namespace - Usage

The System.Data.Odbc namespace provides a data provider that allows you to access data from any ODBC-compliant data source. This is particularly useful for connecting to legacy databases or systems that don't have a specific .NET data provider.

Key Classes and Concepts

The primary classes you'll work with are:

Connecting to an ODBC Data Source

To connect to a data source, you need a valid ODBC connection string. This string typically includes the driver name and the data source name (DSN) configured on the system, or the full connection details.

Example Connection String

Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\Databases\MyDatabase.accdb;

Or for a DSN:

DSN=MyDataSourceName;Uid=myuser;Pwd=mypassword;

Basic Usage Example: Executing a Query

Here's a C# example demonstrating how to connect to an ODBC data source, execute a SELECT query, and read the results:

C#
VB.NET

using System;
using System.Data.Odbc;

public class OdbcExample
{
    public static void Main(string[] args)
    {
        string connectionString = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\\Databases\\Sample.accdb;";
        string query = "SELECT CustomerID, CompanyName FROM Customers WHERE City = 'London'";

        using (OdbcConnection connection = new OdbcConnection(connectionString))
        {
            using (OdbcCommand command = new OdbcCommand(query, connection))
            {
                try
                {
                    connection.Open();
                    using (OdbcDataReader reader = command.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                Console.WriteLine($"CustomerID: {reader["CustomerID"]}, CompanyName: {reader["CompanyName"]}");
                            }
                        }
                        else
                        {
                            Console.WriteLine("No rows found.");
                        }
                    }
                }
                catch (OdbcException ex)
                {
                    Console.WriteLine($"An error occurred: {ex.Message}");
                }
            }
        }
    }
}
                

Imports System
Imports System.Data.Odbc

Public Class OdbcExampleVB
    Public Shared Sub Main(args As String())
        Dim connectionString As String = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\Databases\Sample.accdb;"
        Dim query As String = "SELECT CustomerID, CompanyName FROM Customers WHERE City = 'London'"

        Using connection As New OdbcConnection(connectionString)
            Using command As New OdbcCommand(query, connection)
                Try
                    connection.Open()
                    Using reader As OdbcDataReader = command.ExecuteReader()
                        If reader.HasRows Then
                            While reader.Read()
                                Console.WriteLine($"CustomerID: {reader("CustomerID")}, CompanyName: {reader("CompanyName")}")
                            End While
                        Else
                            Console.WriteLine("No rows found.")
                        End If
                    End Using
                Catch ex As OdbcException
                    Console.WriteLine($"An error occurred: {ex.Message}")
                End Try
            End Using
        End Using
    End Sub
End Class
                

Using Parameters

To prevent SQL injection and improve performance, it's highly recommended to use parameters for your queries.

C#
VB.NET

using System;
using System.Data.Odbc;

public class OdbcParameterExample
{
    public static void Main(string[] args)
    {
        string connectionString = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\\Databases\\Sample.accdb;";
        string query = "SELECT CustomerID, CompanyName FROM Customers WHERE City = ?"; // Using '?' as placeholder

        using (OdbcConnection connection = new OdbcConnection(connectionString))
        {
            using (OdbcCommand command = new OdbcCommand(query, connection))
            {
                // Add the parameter
                command.Parameters.AddWithValue("?", "Paris"); // Value to bind to the placeholder

                try
                {
                    connection.Open();
                    using (OdbcDataReader reader = command.ExecuteReader())
                    {
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                Console.WriteLine($"CustomerID: {reader["CustomerID"]}, CompanyName: {reader["CompanyName"]}");
                            }
                        }
                        else
                        {
                            Console.WriteLine("No rows found for the specified city.");
                        }
                    }
                }
                catch (OdbcException ex)
                {
                    Console.WriteLine($"An error occurred: {ex.Message}");
                }
            }
        }
    }
}
                

Imports System
Imports System.Data.Odbc

Public Class OdbcParameterExampleVB
    Public Shared Sub Main(args As String())
        Dim connectionString As String = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=C:\Databases\Sample.accdb;"
        Dim query As String = "SELECT CustomerID, CompanyName FROM Customers WHERE City = ?" ' Using '?' as placeholder

        Using connection As New OdbcConnection(connectionString)
            Using command As New OdbcCommand(query, connection)
                ' Add the parameter
                command.Parameters.AddWithValue("?", "Paris") ' Value to bind to the placeholder

                Try
                    connection.Open()
                    Using reader As OdbcDataReader = command.ExecuteReader()
                        If reader.HasRows Then
                            While reader.Read()
                                Console.WriteLine($"CustomerID: {reader("CustomerID")}, CompanyName: {reader("CompanyName")}")
                            End While
                        Else
                            Console.WriteLine("No rows found for the specified city.")
                        End If
                    End Using
                Catch ex As OdbcException
                    Console.WriteLine($"An error occurred: {ex.Message}")
                End Try
            End Using
        End Using
    End Sub
End Class
                

Error Handling

It's crucial to handle potential OdbcExceptions that can occur during connection or command execution. Always wrap your ODBC operations in try-catch blocks.

Best Practices

Related API References