Using MySQL with Your ASP.NET Applications [con't]
The Login Form
Start a new ASP.NET project in Visual Studio 2008 and call it MySQLLogin or any other name you prefer. Then create three forms:
- Login.aspx
- Login_do.aspx
- Error_page.aspx
Next, add a HTML table with four rows and two columns. Then add two labels and name them username and password, respectively. When you have done that, add two textboxes and name them uname and upass, respectively. Finally, add a button and name it login_btn. Your form should look something like this:
Now that we have the design of the login form covered, let's get to the code. Before we actually start coding, we need to add a reference to MySQL that will enable us to use it on our login system. To do this, go to website->Add reference. A dialog should pop up with several tabs. On the .NET tab, select the MySQL.DATA component name and click OK. Next, we add some imports to our project:
If we did not add the MySQL.DATA reference to our project, then we would not be able to use MySQL at all. We would not be able to import the MySQL.DATA.MySQLClient namespace either.
Now we set up the database connection variables, like so:
The MySQLConnectionString is responsible for holding the connection parameters for the database. The mycon string is responsible for holding the connection to MySQL. These are two of the most important connection variables. The rest are pretty standard database connection references. Your entire code for the page looks something like this:
Now go to the design of this page and double click on the button and add the following code:
The code above is at the heart of this page and should be easily understandable for those who have used Visual Studio before. Nevertheless, let's take a closer look at the code:
First, we add the connection string to the mycon variable and then we open the connection:
Then we create a SQL statement that checks if the user that wants to log in actually exists in the database:
We then execute the SQL statement using the data reader that we created earlier:
Now we check if any results have been returned by the SQL statement using the HasRows property of the data reader. If results exist, we redirect the user to another page:
If no results were returned, we either show an error message on the current page or redirect the user to an error page and close the connections to the server:
For the error_page.aspx page, simply add this line of code:
A user gets to this page if his or her login details do not match.
Conclusion
After you go through the initial setup, using MySQL with ASP.NET is extremely easy. You can further extend this simple example to include in your own projects.
Original: March 26, 2010

Find a programming school near you