Electronic and Electric Circuit Simulation
Home C Sharp Code Examples c sharp odbc connection
c sharp odbc connection PDF Print E-mail

 

When there is a need to program databases in C# we can access given database either by

or by using ODBC connection. ODBC - Open Database Connectivity is Microsoft interface for accessing database management systems (DBMS). Approach is equivalent, but connection is much easier with odbc connection rather then direct connection to database. In here, small console C# application for database connection via odbc is given. To make it simple (but reliable), DSN (Data source name) in this example is fixed in the string. Namespace System.Data.Odbc has to be included.

string str_odbc = "DSN=freqacc";
OdbcConnection DbConnection = new OdbcConnection(str_odbc);
String str_query = "select * from table ";
OdbcCommand DbCommand = DbConnection.CreateCommand();
DbCommand.CommandText = str_query;

Now, catch is to use try-catch structure in C# in order to see error fro exception ex.

try
{

DbConnection.Open();

OdbcDataReader DbReader = DbCommand.ExecuteReader();

while (DbReader.Read())
{

Console.WriteLine(DbReader["name"].ToString().ToString());

}
DbConnection.Close();
Console.WriteLine("Succeed!");
Console.ReadKey();

}
catch (OdbcException ex)
{

Console.WriteLine("connection to the DSN '" + str_odbc + "' failed.");
Console.WriteLine("The OdbcConnection returned the following message");
Console.WriteLine(ex.Message);
Console.ReadKey();
return;

}

Whole code is:

static void Main(string[] args)
{

string str_odbc = "DSN=freqacc";
OdbcConnection DbConnection = new OdbcConnection(str_odbc);
String str_query = "select * from  table ";
OdbcCommand DbCommand = DbConnection.CreateCommand();
DbCommand.CommandText = str_query;

try
{

DbConnection.Open();

OdbcDataReader DbReader = DbCommand.ExecuteReader();

while (DbReader.Read())
{

Console.WriteLine(DbReader["name"].ToString().ToString());

}

DbConnection.Close();
Console.WriteLine("Succeed!");
Console.ReadKey();

}
catch (OdbcException ex)
{

Console.WriteLine("connection to the DSN '" + str_odbc + "' failed.");
Console.WriteLine("The OdbcConnection returned the following message");
Console.WriteLine(ex.Message);
Console.ReadKey();
return;

}

}

External links:

C# odbc Connection on Easysoft
C# odbc Connection on Microsoft
C# odbc Connection on Dotnetperls

 

 
Copyright © 2014 Electronic and Electric Circuit Simulation. All Rights Reserved.
Joomla! is Free Software released under the GNU/GPL License. Top joomla 1.5 themes
Top joomla 1.5 themes designed by Lonex.

Recent/Mostly Visited

Simulate recent1: Differential Amplifier

Simulate recent2:Instrumentation Amplifier

Simulate recent3:Forward Converter