Displaying Database Results
9 May 2008 @ 09:31AM

Updated: 25 Jan 2010 @ 09:31AM
Now it's time to display our database records. After all, what's the point of storing the comments in a table if we can't pull them out? Let's begin by creating a new method.


Setting Up a New Method

You can see that on line 20 I inserted a call to a new method, showComments(). I then created the method on line 36, though I haven't done much with it yet. I'm now going to add in the code to connect to the database and pull our information out.


Getting the Data

This is pretty much what we did in our insert. I'm running a simple SQL select statement instead of an insert and I've written the connection code to use up a bit less space. One other thing I did was to create the OleDbDataReader dr object on line 49, outside of the try block. The reason is that I have to move the dr.Dispose() method out of the try / catch block. As I mentioned before, if I created dr within the try block I would have to dispose of it in the try block. However, for a select statement I need it to stick around for a bit because it'll hold the data I need. I'm not actually doing anything with the data yet. That's next.
Comments (0)

Displaying the Data

I've added lines 56-65. On lines 56 and 65 I just create the html structure for a table. The magic happens on lines 57-64. With the command while(dr.Read()) I set up a while loop. The way this works is that our select statement is executed and each row is stored inside the OleDbDataReader object dr. When we invoke dr.Read(), it causes dr to move on to the next row of data. When it has no more rows of data, the while loop ends and we continue executing code on line 65. On lines 60-62 we then actually get the data out of dr. Using GetValue accesses the data at the specific offset. For instance, GetValue(0) gets the first piece of data in that row. GetValue(1) gets the second, etc. It's important to remember that GetValue starts counting from 0, not 1.

In effect, what we're doing is retrieving the name, comment and commentDate from the database for all rows. When we invoke dr.Read(), we advanced to the first return row. We then spit out the commentDate, the name and the comment. Dr then advances to the next row and we repeat the process until dr has no more rows left.

Go ahead and play with the code some. You've just completed some very basic database operations. Congratulations! Next we make our site actually look a bit better.
Comments (0)