Click here to Skip to main content
Email Password   helpLost your password?

Introduction

Accessing database is pretty simple job using C# and ADO. In this article, the sample gives you the guidelines for a C# programmer which demonstrates how to use ADO.NET objects including ADOCOnnection, ADOCommand, ADODataReader. Microsoft Data Access Technology got changed with the ADO.NET I access database Employee.mdb, which has a table called "Employee". I will add the employee information to the database .

Using the Code

To write a code in ADO you need to use the following at the beginning of your code.

using System;
using System.Drawing;
using System.ComponentModel;
using System.WinForms;
using System.Data.ADO ;
using System.Data ;
using System.Threading ;

Proceeding with the next step, make sure that all of your GUI is in place for adding the data ( all the text boxes and labels , that is pretty simple so I am not going to cover this), Next will will go ahead and get the connection to the database( note the connection to the database should be running on a different thread, so that it will not mess up the GUI. to do this we have to start a thread as shown below.

ThreadStart DBThread = new ThreadStart(ConnectToDatabase) ;
        Thread DB = new Thread(DBThread) ;
        DB.Start() ;

As you can see above we have successfully started the thread, This thread calls the method ConnectToDataBase, let see what this ConnectToDatabase method is all about.

  public void ConnectToDatabase()
  {
      Infobar.Text="Please Wait, Connecting to database...." ;
      string conn=
"Provider=Microsoft.Jet.OLEDB.4.0 ;Data Source=Employee.mdb" ;
      // here we create a new ADOConnection  

      // Object which takes the connection string

        ADOConnection dbConn = new ADOConnection(conn) ;
        
        //Make a Select Command

        string empStr = "Select id from Employee" ;
        // creates a new ADOCommand object which takes 

        // a string and connection

        ADOCommand sqlCommand =new ADOCommand(empStr,dbConn);
        // finally open the connection to the database

        dbConn.Open();
        //now it's time to read some data from the database, 

        //which can be done as shown below.

        ADODataReader reader;
        
        //Execute the command and get the Data into "reader"

        sqlCommand.Execute(out reader) ;
        int numRecords=0 ;
        //Get the current number of records present in the database.

        while(reader.Read())
        {
          numRecords++ ;
        }
        numRecords++ ;
        //update the employee Id textbox with the Number 

        //of records present plus one.

        employeeID.Text = numRecords.ToString() ;
        
        Infobar.Text="Connected - Now you can Add records";
  }
Hope the above code is not much confusing, It is lot simpler than writing the code in VC++ ADO. now it's time to write a method that actually takes all the parameters from the GUI Form and writes it to the database with the click of a button. for this we will create a button called Add In your InitializeComponents Method the code would look like this
Add.Text = "AddToDatabase";
Add.Click += new System.EventHandler(WriteToDataBase);
This gets as simple as it looks, Actually writing to database is much simpler as shown below in the code.
 protected void WriteToDatabase(object sender, System.EventArgs e)
  {
    
    if(employeeID.Text!=""&&employeeLastName.Text!=""
      &&employeeFirstName.Text!=""&&employeeAge.Text!=""
      &&employeeSSN.Text!="")
    {
        
      string conn="Provider=Microsoft.Jet.OLEDB.4.0 ;"+
                "Data Source=Employee.mdb" ;
      // get the connection object and open the connection

      ADOConnection dbConn = new ADOConnection(conn) ;
      dbConn.Open();
      //prepare a statement to get all the values from the text boxes.

      string strInsert = "INSERT INTO Employee (employeeID, " + 
        "employeeLastName, employeeFirstName, "+
        "employeeAge, employeeSSN) VALUES ( "
        +employeeID.Text+", '"
        +employeeLastName.Text+"' , '"
        +employeeFirstName.Text+"' , "
        +employeeAge.Text+", "
        +employeeSSN.Text+")";
        
      ADOCommand adoInsert = new ADOCommand(strInsert,DBConn) ;
      //Execute the statement 

      adoInsert.ExecuteNonQuery() ;
      Infobar.Text="Data is being Added to Database " ;
      // after adding the data to the database we need to reset all 

      //the data from the text boxes or to say clear the fields in the 

      // text boxes so that we can add again.

      int iClear=int.Parse(employeeID.Text);
      iClear++;
      employeeID.Text=i.ToString() ;
      employeeLastName.Text="" ;
      employeeFirstName.Text="" ;
      employeeAge.Text="" ;
      employeeSSN.Text="" ;
      Infobar.Text="Connected - Now you can Add more records...";
      DBConn.Close() ;
    }
    else
    {
      MessageBox.Show("All fields must be filled.", "Error",
         MessageBox.IconExclamation);
    }
  }

Hope this was helpful. Will write more on how to view the database values and how to delete those values in my coming articles.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralMy vote of 1
JaneDoe
4:25 7 Jun '09  
Somehow I think you can connect to a database without creating a thread. And I assume there is an elegant way of inserting data other then a hard-coded INSERT statement.
I'm new to C# and .NET and have a strange filling I'm being misled by this article
GeneralMy vote of 2
Bart19801234
22:52 30 Nov '08  
double connection; INSERT command hardcoded insted of demonstration how to use params
QuestionStop double login to SQL Server.
A H Khan
23:06 27 Jun '06  

Hi all

I am developing a desktop application in C# using SQL Server at backend, i need to stop my users to get double login to the system, i have been doing it in Borland Delphi but still confused Confused to do in c#, can any one let me know with code example ...

Thanks

AHKhan.Confused
GeneralAccess database from C#.Net via ODBC
Will L Pittenger
23:46 12 Oct '04  
I have started work on a C#.Net application which would use an Access database. I have written MFC (4.x through 6.x) applications which used derived recordsets for each table or join and unbound controls (bound controls were problematic).

I liked the derived recordset/unbound controls combination and was thinking of using it for my C# app. However, I have not figured out how to derive my recordsets (or even what the correct C# equivalent would be). I think the unbound part myself, but I do not even know if ODBC is the best way to get at my database. (I did create a ODBC datasource and tell Visual Studio about it. However, Visual Studio does not seem to have any C# wizard to create a derived recordset from the table like I used with MFC.

Any suggestions would be helpful.Smile

--------------
Will Pittenger
Generalerror message
domza
1:14 27 Sep '04  
Confused Hi I also have a problem in compiling the application.
errors are on the system.data.ado and system.Winform.

my application is a web application developed in C# please help.
GeneralFew more details
Md Saleem Navalur
1:33 14 Jun '04  
hi,

Iam new to C# and .NET.
Can u give a sample which demonstrates Add, modify, delete and fetch data from the database using SQL statements, with the complete UI.

Your help will be greatly appreciated.

Thanx in advance
saleem

GeneralError Message Appear
softman2002
0:08 2 Mar '04  
Hi,

There is a question in me. I've tryed to compile the example published in this section, but there was few error messages Appear in the lines:

"using System.Data.ADO" and "using System.WinForms"

Please, help me. What I have to do to correct the errors?

10x Smile

Ivo from BG
GeneralRe: Error Message Appear
domza
1:18 27 Sep '04  
Just wanted to know if you managed to fix the error.
If you did please send me the corrected version of the application.

your help will be highly appreciated.

domza from SAConfused
GeneralHave one question to expand upon on this article
michin1
6:33 27 Oct '03  
Your article was very helpful thank you for posting it.

I have a question regarding passing a parameter to the database thread

ThreadStart DBThread = new ThreadStart(ConnectToDatabase) ;
Thread DB = new Thread(DBThread) ;
DB.Start() ;


What if I wanted to pass a variable to this threaded function lets say strIdentifier and do something like below, where strIdentifier is not associated with the GUI, but passed to the thread?

string strInsert = "INSERT INTO Employee (employeeID, employeeLastName, employeeFirstName, employeeAge, employeeSSN) VALUES ( "
+employeeID.Text+", '"
+employeeLastName.Text+"' , '"
+employeeFirstName.Text+"' , "
+employeeAge.Text+", "
+strIdentifier+", "
+employeeSSN.Text+")";
GeneralNice Article. Neately explained
Dave Marcus
12:54 25 Jan '03  
will appreciate if you can upate with Deletion of records and Editing of records.Smile
GeneralOld version of .NET!
Rickard Andersson
12:51 25 Jan '03  
Why are you posting an article about how you do database programing with the BETA version of the .NET Framework? Confused Dead


Rickard Andersson@Suza Computing C# and C++ programmer from SWEDEN! UIN: 50302279
E-Mail: nikado@pc.nu Speciality: I love C#, ASP.NET and C++!

GeneralRe: Old version of .NET!
leppie
22:08 25 Jan '03  
Yeah I noticed that too Unsure

Who is this miscrosoft, and what devilish plans have they for us?


Last Updated 25 Jan 2003 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010