Search

Sunday, September 15, 2013

ODBC connectivity in C#

Hi,
    I assume that you have already installed MySQL/ORACLE and their respective ODBC driver . Along with this basic knowledge of SQL queries.
Now, lets get started with C# ODBC connectivity.

1. Before writing any code , you need to include correct namespace.  
      using System.Data.Odbc;

2. For creating connection we will be using OdbcConnection class.


3. create string which will contain all required parameters for ODBC connection.
 like, Data Source Name(DSN), Driver, UID, Database name, password. Depending on type of driver you are using there will be little bit change in connection string.
example:
   string connection=" Driver={MySQL ODBC 5.2w Driver};Server=localhost;Database=DataBase_Name;User=myUsername;Password=myPassword;Option=3;  

OR
Goto Control Panel -> Administrative tools -> Data Sources(ODBC) -> Select User DSN tab->Add -> select required driver and test connection.

string connection="dsn=dsn_name;"

4. Now,

    pass this connection string to OdbcConnection constructor.
OdbcConnection= objOdbcConnection= new OdbcConnection(connection);

5. 
try
{
     connection.open();

// Perform Operation as per your requirement.

     connection.close();
}
catch(OdbcException e)
{
      console.writeLine(e.Message);
}

6. After opening connection you need to create command ,

OdbcCommand objOdbcCommand= connection.createCommand();
objOdbcCommand.CommandText="select * from table_name";
OdbcDatareader objOdbcDataReader= objOdbcCommand.ExecuteReader();
while(objDatareader.read())
{
    console.writeLine(objOdbcdataReader.GetString(0));
}

I hope this information will reduce your searching effort and you will get started with your ODBC connectivity ASAP.

                                                                                                                                      -Cheers.

No comments:

Post a Comment