C# to Access 2007 Connector

This post contains how to Connecting C# Language to DBMS using Microsoft Access 2007

Software and Tools used on this post

  1. Programming Language : C# .NET 3.5
  2. IDE : Microsoft Visual Studio 2008
  3. DBMS : Microsoft Access 2007 (.accdb) or (.mdb)

First what we need is connector to DBMS

using System.Data.OleDb;

Then the object which make connection

public static OleDbConnection con;

And the method for connecting to DBMS Microsoft Access 2007

        public static void ConnectToDatabase()
        {
            con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;" +
                "Data Source=./Database/data.accdb;" +
                "Persist Security Info=False");
        }

What about executing query? Look at this…

        private void button_login_Click(object sender, EventArgs e)
        {
            Program.con.Open();

            OleDbCommand cmd = Program.con.CreateCommand();
            cmd.CommandText = "SELECT * FROM user_login WHERE ID='Administrator'";

            OleDbDataReader reader = cmd.ExecuteReader();

            if (reader.Read())
            {
                String password = reader.GetString(1);
                String input = text_password.Text.GetHashCode().ToString();

                if (password.CompareTo(input) != 0)
                {
                    MessageBox.Show("Password Incorrect");
                }
                else
                {
                    Program.mainmenu = new Main();
                    Program.mainmenu.Show();
                    this.Hide();
                }
            }
            else
            {
                MessageBox.Show("Error (22) : Administrator Login not found");
                Environment.Exit(22);
            }

            Program.con.Close();
        }

And still many more method like ExecuteNonQuery() for DML

Leave a Reply

Your email address will not be published. Required fields are marked *

Post Navigation