Connecting to an Access Database with C#

Start with a new C# windows application in Visual Studio. Call it “AccessDBTutorial”. Download the sample Access database I have created for you from this URL: http://www.informatics.indiana.edu/yrogers/pervasive/downloads/people.mdb This database “people.mdb” consists of exactly one table called “students”, which looks like this:
username aalkasim aashok akalafut amutsudd anmcleve bkopecky cshue dwolfe gmawalan gweldon jebonner jiadeng kbrunett kmakice mbuddie mpgandhi prohwer rkale rvarick san shahak sskamath tjtucker ttoscos vvasudev Firstname Alia Arvind Andrew Adity Anne Brian Craig Daniel Gauri Matt Josh Jiahu Kynthia Kevin Michele Mona Paul Rupali Ryan Shunying Ankur Shreyas Tim Tammy Varun lastname Al Kasimi Ashok Kalafut Upoma Faber Kopecky Shue Wolfe Mawalankar Weldon Bonner Deng Brunette Makice Buddie Gandhi Rohwer Kale Varick An Shah Kamath Tucker Toscos Vasudev department CS HCI CS CS CS CS CS MIME CS HCI CS CS HCI HCI MIME CS CS CS HCI HCI CS CS HCI HCI CS email aalkasim@indiana.edu aashok@indiana.edu akalafut@indiana.edu amutsudd@indiana.edu anmcleve@indiana.edu bkopecky@indiana.edu cshue@indiana.edu dwolfe@indiana.edu gmawalan@indiana.edu gweldon@indiana.edu jebonner@indiana.edu jiadeng@indiana.edu kbrunett@indiana.edu kmakice@indiana.edu mbuddie@indiana.edu mpgandhi@indiana.edu prohwer@indiana.edu rkale@indiana.edu rvarick@indiana.edu san@indiana.edu shahak@indiana.edu sskamath@indiana.edu tjtucker@indiana.edu ttoscos@indiana.edu vvasudev@indiana.edu project_group 7 3 7 3 8 2 5 2 6 5 5 6 2 7 3 8 6 2 6 8 3 6 5 8 7

We are going to create a very simple C# application that issues an SQL query to this database and returns the result. It should look very similar to this ☺, Thanks Tammy for being the example.

Lets get started…

The first thing we need to do is make a connection to the Access database (people.mdb), open the Server Explorer by clicking (Ctrl+Alt+S). From the list right-click Data Connections and choose 'Add Connection...'. In the 'Provider' tab select Microsoft Jet 4.0 OLE DB Provider (used for connecting to an Access database), and click Next. Use the '...' button to browse for an Access Database and choose the database you have downloaded, people.mdb. After clicking OK, test the connection by clicking the 'Test Connection' button. It should say 'Test connection succeeded.’ Press OK and a window pops up that says 'Please Enter MS JET OLE DB Initialization Information'. Leave the defaults and just press OK.

Just like you see in the above screenshot, you can browse the Access file database. Yet the database is not connected to our program. For this you need to drag the node below 'Data Connections' on the form. The node is named using the form 'ACCESS.X:\PathToYourDatabase\people.mdb.Admin'. As I said, drag it on the form and 'oleDbConnection1' should appear below the form:

Next open the Toolbox (Ctrl+Alt+X) and from the 'Data' group drag an 'OleDbDataAdapter'. The 'Data Adapter Configuration Wizard' starts. Clicking next will take you to the part where you need to select the connection you wish to use. Choose the connection we have just created (ends up in people.mdb.Admin). Press Next and then again Next (leave the default 'Use SQL statements').

Now you are being asked 'What data should the data adapter load in the dataset?'. We want all the tables and all the columns therefore we need to take the following steps. Open the Query Builder using the button and you should now be able to add the table named 'students'. Add it and close the small window and now we have a small window representing the table. We want to select all the columns, therefore check '* (All Columns)'. The following SQL query is created: SELECT students.* FROM students We could also do it more simple by typing 'SELECT * FROM students'... it would have been the same. Press OK to exit the Query Builder and then press Finish. Now add a DataSet to our application by dragging one from the Data group (Toolbox). Choose 'Untyped DataSet (no schema)'. DataSets are used to store the query results. Now create a form that looks like this:

label1 label2 button1 textfield1

Now doubleclick button1 so we can put code into the button1_Click event. First we should set the string we’ll use for our SQL query: String sqlQuery = "SELECT firstname,lastname,email FROM students where username = \'"+textBox1.Text.ToString()+" \'";

now, set the SQL query in our oleDbDataAdaptor… oleDbDataAdapter1.SelectCommand.CommandText = sqlQuery; Next we clear the DataSet preparing it for the operation dataSet1.Clear(); Next we use the 'Fill()' method of oleDbDataAdapter1 to fill the dataSet1 with the result of the SQL query: int numberOfRowsFeched = oleDbDataAdapter1.Fill(dataSet1, "students"); the Fill() method returns the number of rows that were fetched when the query was run, notice that we captured it as numberOfRowsFeched. At this point we have a DataSet with the result of our query in it, to get at the data inside there we have to use an object called DataTable. So, add these lines below what you have already… if (numberOfRowsFeched > 0) { DataTable dt = dataSet1.Tables["students"]; label1.Text = dt.Rows[0][0].ToString() + " " + dt.Rows[0][1].ToString(); label2.Text = dt.Rows[0][2].ToString(); } else { label1.Text = "Name not found."; label1.Text = ""; } Here is all the code we wrote in one place: private void button1_Click(object sender, System.EventArgs e) { sqlQuery = "SELECT firstname,lastname,email FROM students where username = \'"+textBox1.Text.ToString()+" \'"; oleDbDataAdapter1.SelectCommand.CommandText = sqlQuery; dataSet1.Clear(); numberOfRowsFeched = oleDbDataAdapter1.Fill(dataSet1,"students"); if (numberOfRowsFeched > 0) { DataTable dt = dataSet1.Tables["students"]; label1.Text = dt.Rows[0][0].ToString() + " " + dt.Rows[0][1].ToString(); label2.Text = dt.Rows[0][2].ToString(); } else { label1.Text = "Name not found."; label1.Text = ""; } }

Now, run your program to see if it works!!!

Your assignment: Add a PhidgetRFID sensor to this project, and find out the ID of 5 RFID tags, associate those tags with some of the records in the people.mdb database. Once you have the records in the database tagged, add some code to the application you created above, and make it so that when you detect an RFID object the application queries that record from the database. Hints: When the RFID sensor detects an RFID object it calls the rfid1_Tag function repeatedly, you’ll need to make a way that it only calls the SQL query once. Spit the values from your RFID tags to System.Console.Writeline so you can see them, and copy and paste them into some text editor so you can add them to the database. My final Form looks like this after I touch one of my RFID tags to the RFID reader…

010238ed56

Sign up to vote on this title
UsefulNot useful