Tuesday, July 31, 2012

How to connect C# with MS Access database using OledbConnection

1 : Include Files:

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

2 : Declare variables that intract with DB

        OleDbConnection conn;
        OleDbCommand comm = new OleDbCommand();
        DataTable dt = new DataTable();
        OleDbDataAdapter da = new OleDbDataAdapter();

3 : Write a method to  Create Connection

private void CreateConnection()
 conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;data source=d:\\sms.mdb");
         if (conn.State == ConnectionState.Closed)
            comm.CommandType = CommandType.Text;
            comm.Connection = conn;
4 : Write your method to function with the DB
I am using to insert some data in DataBase

public int SaveSMS(int number, string SMS)
            int result = -1;
     comm.CommandText = "insert into SMSBundle (MobileNo,SMSText) values (@number,@SMS)";
                comm.Parameters.Add(new OleDbParameter("@number", number));
                comm.Parameters.Add(new OleDbParameter("@SMS", SMS));
                result = comm.ExecuteNonQuery();

                return result;
            catch (Exception)
                return -1;

Simple App Test:
This app will simply save a mobile number and an sms in the MS Access DB. Please put the sms.mdb file in D:\ as i have used the static path.


No comments:

Post a Comment