Sunday, February 20, 2011

CSharp ODBC Example

using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Odbc;

namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
if (args.Length != 1 )
{
Console.WriteLine("usage: program connection-string");
return;
}

String connStr = args[0];

OdbcConnection DbConnection = new OdbcConnection( connStr );

try
{
DbConnection.Open();
}
catch (OdbcException ex)
{
Console.WriteLine("connection to the data source '" + connStr + "' failed.");
Console.WriteLine("The OdbcConnection returned the following message");
Console.WriteLine(ex.Message);
return;
}

Console.Write("SQL> ");
String query = Console.ReadLine();

OdbcCommand DbCommand = DbConnection.CreateCommand();

DbCommand.CommandText = query;

try
{
OdbcDataReader DbReader = DbCommand.ExecuteReader();

int fCount = DbReader.FieldCount;

Console.Write(":");
for (int i = 0; i < fCount; i++)
{
String fName = DbReader.GetName(i);
Console.Write(fName + ":");
}
Console.WriteLine();

while (DbReader.Read())
{
Console.Write(":");
for (int i = 0; i < fCount; i++)
{
String col = DbReader.GetString(i);
Console.Write(col + ":");
}
Console.WriteLine();
}

DbReader.Close();
}
catch (OdbcException ex)
{
Console.WriteLine("Executing the query '" + query + "' failed.");
Console.WriteLine("The OdbcCommand returned the following message");
Console.WriteLine(ex.Message);
return;
}

DbCommand.Dispose();
DbConnection.Close();
}
}
}

No comments:

Post a Comment