Database Access Improved
9 May 2008 @ 09:25AM
Updated: 25 Jan 2010 @ 09:25AM
On the previous page we created a very basic connection to the database. There are a few problems with it, however. What happens if the connection doesn't work? You can change the Data Source in the
connectionString to something incorrect to see. Basically you get a big, ugly error. So we'll start with error handling.

Error Handling
So I've wrapped the
conn.Open() command in a
try/catch block. That way if the
Open() doesn't work, instead of throwing a huge ugly error and stopping the web application from running, I just write out "There was an error connecting to the database.", return the string, and my code keeps executing. Note that I used
return content; on line 60. Basically I just set the
content variable and then returned it, thereby ceasing further execution of the
form() method. This takes us back to
Page_Load where the remainder of our web app continues to execute.
I wrapped another
try/catch block around the
OleDbDataReader dr = cm.ExecuteReader() section. That way if I execute the SQL and the SQL has a mistake in it, the error doesn't break our web app. Instead I display a simple error and continue executing the rest of the web app. Note that I put the
dr.Dispose() command inside the try block along with where
dr was defined. Basically, because I created the
OleDbDataReader dr inside this try block, I can only act on it inside this try block. If you put the
dr.Dispose() command outside of the try, you'll get an error message. This is called variable scope. It's a bit beyond what we're doing in this tutorial so I won't go into it much, but it's something to keep in mind.
So go ahead and use the form. Enter your name and comment and hit submit. If all goes well you should get the "Thanks for submitting" message. Go ahead and go to SQL Server Management Studio Express. Log into the server if you're not currently logged in. Open up the Databases dropdown (if it's not already open) and highlight our Guestbook database. Next, click the "New Query" button in the toolbar on the top left. Alternately, you can go to File | New | Query With Current Connection. A white page will open on the right. Type in "select * from comments", then hit Excecute in the toolbar or hit F5.

Rows In Your Database
The results of the query display below. You should see a row for every time you filled out that form and hit submit. This is our persistent data. Congratulations! If for some reason you're having problems getting this to work, I'm providing a link to my source code.
Codefile [Default.aspx.zip]
So, are we done? Absolutely not. The next page will cover an extremely important aspect of web development: security.