Sei sulla pagina 1di 5

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 Firstname lastname department email project_group
aalkasim Alia Al Kasimi CS aalkasim@indiana.edu 7
aashok Arvind Ashok HCI aashok@indiana.edu 3
akalafut Andrew Kalafut CS akalafut@indiana.edu 7
amutsudd Adity Upoma CS amutsudd@indiana.edu 3
anmcleve Anne Faber CS anmcleve@indiana.edu 8
bkopecky Brian Kopecky CS bkopecky@indiana.edu 2
cshue Craig Shue CS cshue@indiana.edu 5
dwolfe Daniel Wolfe MIME dwolfe@indiana.edu 2
gmawalan Gauri Mawalankar CS gmawalan@indiana.edu 6
gweldon Matt Weldon HCI gweldon@indiana.edu 5
jebonner Josh Bonner CS jebonner@indiana.edu 5
jiadeng Jiahu Deng CS jiadeng@indiana.edu 6
kbrunett Kynthia Brunette HCI kbrunett@indiana.edu 2
kmakice Kevin Makice HCI kmakice@indiana.edu 7
mbuddie Michele Buddie MIME mbuddie@indiana.edu 3
mpgandhi Mona Gandhi CS mpgandhi@indiana.edu 8
prohwer Paul Rohwer CS prohwer@indiana.edu 6
rkale Rupali Kale CS rkale@indiana.edu 2
rvarick Ryan Varick HCI rvarick@indiana.edu 6
san Shunying An HCI san@indiana.edu 8
shahak Ankur Shah CS shahak@indiana.edu 3
sskamath Shreyas Kamath CS sskamath@indiana.edu 6
tjtucker Tim Tucker HCI tjtucker@indiana.edu 5
ttoscos Tammy Toscos HCI ttoscos@indiana.edu 8
vvasudev Varun Vasudev CS vvasudev@indiana.edu 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

Potrebbero piacerti anche