Connect to an Access database file

image_pdfimage_print
   

using System;
using System.Data;
using System.Data.OleDb;

class AccessConnect {
   static void Main() 
   {
      string connString = @"provider = microsoft.jet.oledb.4.0;data source = Employee.mdb;";

      OleDbConnection conn = new OleDbConnection(connString);

      try 
      {
         conn.Open();
         Console.WriteLine("Connection opened.");

         Console.WriteLine("Connection Properties:");   
         Console.WriteLine("	Connection String: {0}", conn.ConnectionString);    
         Console.WriteLine("	Database: {0}",conn.Database);   
         Console.WriteLine("	DataSource: {0}",conn.DataSource);
         Console.WriteLine("	ServerVersion: {0}", conn.ServerVersion);
         Console.WriteLine("	State: {0}", conn.State);
      } catch (OleDbException e) {
         Console.WriteLine("Error: " + e);  
      } finally  {
         conn.Close();
         Console.WriteLine("Connection closed.");
      }
   }
}



           
          


Read query result data from Access database

image_pdfimage_print
   

using System;
using System.Data;
using System.Data.OleDb;

   class CommandOleDbQuery
   {
      static void Main() 
      {
         OleDbConnection thisConnection = new OleDbConnection("provider = microsoft.jet.oledb.4.0;data source = Employee.mdb;");
      
         OleDbCommand thisCommand = new OleDbCommand("SELECT ID, FirstName FROM Employee",thisConnection);

         try 
         {
            thisConnection.Open();
            OleDbDataReader thisReader = thisCommand.ExecuteReader();

            while (thisReader.Read()) {
               Console.WriteLine("Product ID and Name: {0} {1}",
                  thisReader.GetValue(0),
                  thisReader.GetValue(1));
            }
         } 
         catch (OleDbException ex) 
         {
            Console.WriteLine(ex.ToString());
         }
         finally 
         {  
            thisConnection.Close();
            Console.WriteLine("Connection Closed.");
         }
      }
   }



           
          


Use OdbcCommand to read data in Access database and fill the DataGrid

image_pdfimage_print
   
 

using System;
using System.Diagnostics;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Data.Odbc;


public class Form1 : System.Windows.Forms.Form {
    private System.Windows.Forms.Button button1;
    private System.Windows.Forms.DataGrid dataGrid1;
    private System.Windows.Forms.Button button2;
    public Form1() {
        this.button1 = new System.Windows.Forms.Button();
        this.dataGrid1 = new System.Windows.Forms.DataGrid();
        this.button2 = new System.Windows.Forms.Button();
        ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).BeginInit();
        this.SuspendLayout();

        this.button1.Location = new System.Drawing.Point(8, 240);
        this.button1.Size = new System.Drawing.Size(104, 32);
        this.button1.Text = "Get Data From Biblio";
        this.button1.Click += new System.EventHandler(this.button1_Click);

        this.dataGrid1.DataMember = "";
        this.dataGrid1.HeaderForeColor = System.Drawing.SystemColors.ControlText;
        this.dataGrid1.Location = new System.Drawing.Point(8, 8);
        this.dataGrid1.Size = new System.Drawing.Size(280, 224);

        this.button2.Location = new System.Drawing.Point(120, 240);
        this.button2.Size = new System.Drawing.Size(152, 32);
        this.button2.Text = "Get Data From Access Northwind";
        this.button2.Click += new System.EventHandler(this.button2_Click);

        this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
        this.ClientSize = new System.Drawing.Size(292, 273);
        this.Controls.AddRange(new System.Windows.Forms.Control[] {
                                                                          this.button2,
                                                                          this.dataGrid1,
                                                                          this.button1});
        ((System.ComponentModel.ISupportInitialize)(this.dataGrid1)).EndInit();
        this.ResumeLayout(false);

    }
    [STAThread]
    static void Main() {
        Application.Run(new Form1());
    }

    private OdbcConnection cn;

    private void button1_Click(object sender, System.EventArgs e) {
        try {
            cn = new OdbcConnection("DRIVER={SQL Server};SERVER=.;uid=admin;pwd=pw;database=biblio");
            cn.Open();
            OdbcCommand sc = new OdbcCommand("SELECT title, price FROM titles WHERE title LIKE 'Hi%'", cn);
            OdbcDataAdapter da = new OdbcDataAdapter(sc);
            DataSet ds = new DataSet("TitlesDS");
            da.Fill(ds);
            dataGrid1.DataSource = ds.Tables[0];
        } catch (Exception ex) {
            Debug.WriteLine(ex.ToString());
        } finally {
            cn.Close();
        }
    }

    private void button2_Click(object sender, System.EventArgs e) {
        try {
            cn = new OdbcConnection(@"DRIVER={Microsoft Access Driver (*.mdb)};DBQ=c:NorthWind.mdb");
            cn.Open();
            OdbcCommand sc = new OdbcCommand("SELECT * from Employees", cn);
            OdbcDataAdapter da = new OdbcDataAdapter(sc);
            DataSet ds = new DataSet("TitlesDS");
            da.Fill(ds);
            dataGrid1.DataSource = ds.Tables[0];
        } catch (Exception ex) {
            MessageBox.Show("You probably need to change the file path to NorthWind.MDB used in the OdbcConnection Constructor
 or move a copy of the NorthWind.mdb to c:");
            Debug.WriteLine(ex.ToString());
        } finally {
            cn.Close();
        }
    }
}

    


How to use an OleDbConnection object to connect to an Access database

image_pdfimage_print
   

using System;
using System.Data;
using System.Data.OleDb;

class OleDbConnectionAccess {
  public static void Main() {
    string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;data source=.Northwind.mdb";

    OleDbConnection myOleDbConnection = new OleDbConnection(connectionString);

    OleDbCommand myOleDbCommand = myOleDbConnection.CreateCommand();

    myOleDbCommand.CommandText =
      "SELECT CustomerID, CompanyName, ContactName, Address "+
      "FROM Customers "+
      "WHERE CustomerID = 'ALFKI'";
    myOleDbConnection.Open();

    OleDbDataReader myOleDbDataReader = myOleDbCommand.ExecuteReader();

    myOleDbDataReader.Read();

    Console.WriteLine("myOleDbDataReader[" CustomerID"] = "+ myOleDbDataReader["CustomerID"]);
    Console.WriteLine("myOleDbDataReader[" CompanyName"] = "+ myOleDbDataReader["CompanyName"]);
    Console.WriteLine("myOleDbDataReader[" ContactName"] = "+ myOleDbDataReader["ContactName"]);
    Console.WriteLine("myOleDbDataReader[" Address"] = "+ myOleDbDataReader["Address"]);

    myOleDbDataReader.Close();

    myOleDbConnection.Close();
  }
}



           
          


Reading Access Data

image_pdfimage_print
   
 
using System;
using System.Data;           
using System.Data.OleDb;     
using System.Collections.Generic;
using System.Text;

class Program {
    static void Main(string[] args) {
        OleDbConnection thisConnection = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:
wind.mdb");
        thisConnection.Open();
        OleDbCommand thisCommand = thisConnection.CreateCommand();
        thisCommand.CommandText = "SELECT CustomerID, CompanyName FROM Customers";
        OleDbDataReader thisReader = thisCommand.ExecuteReader();
        while (thisReader.Read()) {
            Console.WriteLine("	{0}	{1}",thisReader["CustomerID"], thisReader["CompanyName"]);
        }
        thisReader.Close();
        thisConnection.Close();
    }
}

    


Compresses/Decompress the specified data.

image_pdfimage_print
   
 

//http://sb2extensions.codeplex.com/
//Apache License 2.0 (Apache)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.IO.Compression;
using System.Runtime.Serialization.Formatters.Binary;

namespace Sb2.Extensions
{
    public static class CompressionExtensions
    {
        /// <summary>
        /// Compresses the specified data.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public static byte[] Compress(this byte[] data)
        {
            using (MemoryStream output = new MemoryStream())
            {
                using (DeflateStream def = new DeflateStream(output, CompressionMode.Compress))
                {
                    def.Write(data, 0, data.Length);
                }
                return output.ToArray();
            }
        }
        /// <summary>
        /// Decompresses the specified data.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public static byte[] Decompress(this byte[] data)
        {
            using (MemoryStream input = new MemoryStream())
            {
                input.Write(data, 0, data.Length);
                input.Position = 0;
                using (DeflateStream def = new DeflateStream(input, CompressionMode.Decompress))
                {
                    using (MemoryStream output = new MemoryStream())
                    {
                        byte[] buff = new byte[64];
                        int read = -1;
                        read = def.Read(buff, 0, buff.Length);
                        while (read > 0)
                        {
                            output.Write(buff, 0, read);
                            read = def.Read(buff, 0, buff.Length);
                        }
                        def.Close();
                        return output.ToArray();
                    }
                }
            }
        }
        /// <summary>
        /// Compresses the specified data.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="data">The data.</param>
        /// <returns></returns>
        public static byte[] Compress<T>(this T data)
        {
            byte[] result = null;
            using (MemoryStream ms = new MemoryStream())
            {
                var formatter = new BinaryFormatter();
                formatter.Serialize(ms, data);
                result = Compress(ms.ToArray());
            }
            return result;
        }
        /// <summary>
        /// Decompresses the specified compressed data.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="compressedData">The compressed data.</param>
        /// <returns></returns>
        public static T Decompress<T>(this byte[] compressedData) where T : class
        {
            T result = null;
            var formatter = new BinaryFormatter();
            byte[] decompressed = Decompress(compressedData);
            using (MemoryStream ms = new MemoryStream(decompressed))
            {
                result = formatter.Deserialize(ms) as T;
            }
            return result;
        }
    }
}