Csharp/C Sharp/Database ADO.net/ODBC
ODBC connection
using System;
using System.Data;
using System.Data.Odbc;
class OdbcProvider
{
static void Main(string[] args)
{
string connString = @"dsn=northwindodbc";
string sql = @"select * from employees";
OdbcConnection conn = null;
OdbcDataReader reader = null;
try {
conn = new OdbcConnection(connString);
conn.Open();
OdbcCommand cmd = new OdbcCommand(sql, conn);
reader = cmd.ExecuteReader();
Console.WriteLine(
"Querying database {0} with query {1}\n"
, conn.Database
, cmd.rumandText
);
Console.WriteLine("First Name\tLast Name\n");
while(reader.Read()) {
Console.WriteLine(
"{0} | {1}"
, reader["FirstName"].ToString().PadLeft(10)
, reader[1].ToString().PadLeft(10)
);
}
} catch (Exception e) {
Console.WriteLine("Error: " + e);
} finally {
reader.Close();
conn.Close();
}
}
}
Odbc Error Handler
using System;
using System.Diagnostics;
using System.Drawing;
using System.Collections;
using System.ruponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.Odbc;
public class MainClass {
[STAThread]
static void Main() {
OdbcConnection cn;
try {
cn = new OdbcConnection();
cn.ConnectionString = "driver={SQL Serve};server=.;uid=admin;pwd=pw;database=biblio";
cn.Open();
} catch (OdbcException ex) {
if (ex.InnerException != null) {
Debug.WriteLine("InnerException:" + ex.InnerException.Message);
}
MessageBox.Show(ex.ToString());
Debug.WriteLine("Message:" + ex.Message.ToString());
Debug.WriteLine("Source:" + ex.Source.ToString());
Debug.WriteLine("StackTrace:" + ex.StackTrace.ToString());
Debug.WriteLine("TargetSite:" + ex.TargetSite.ToString()); // Not in OleDB
if (ex.HelpLink != null) {
Debug.WriteLine("HelpLink:" + ex.HelpLink);
}
}
}
}