Sei sulla pagina 1di 22

A Step-by-Step Guide To Using MySQL with ASP.

NET

Introduction

Back in the days of classic ASP, if you were building a database-driven web site, your choice was either to
invest a lot of money to get a copy of Microsoft SQL Server (or some other enterprise-ready database) or
invest a lot of time finding a way to deal with the performance and scalability limitations of Microsoft
Access. Luckily these days there's another viable alternative: MySQL.

What is MySQL?

MySQL is an open source database server. While many organizations may choose to purchase a
commercial version of the product, the GNU General Public License (commonly known as the "GPL")
ensures that the source code will remain available and therefore the software can be used free of charge
for those willing to forego official support and support it themselves.

For more information, see the MySQL website.

Step 1 - Download and Installation

As with most any software, the first step to getting up and running with MySQL is to obtain and install the
product. You can download the setup file from http://dev.mysql.com/downloads/index.html. As of this
writing the current version is MySQL 4.1 so that's the version I'll be using for the rest of this article.
Unless you have a reason to do otherwise, I'd recommend just downloading the pre-compiled binaries for
you current platform. In this case I'll be installing on a Windows XP machine so I downloaded the normal
Windows version which includes the installer. The download is just under 35 MB so over it shouldn't take
too long to get via any resonable internet connection.

The installation is straight-forward and caused no problems for the very modest laptop I installed it on.
Just so you have an idea of what to expect, I'm including screen captures of several steps of the setup
process.
As you can see in the screen capture above, at the end of the setup process the installer asks if you'd like
to configure the MySQL Server. If you choose to do so, it will launch the MySQL Server Instance
Configuration Wizard which brings us to the next step in the process.

Step 2 - Configuration

The MySQL Server Instance Configuration Wizard makes configuring your server really simple.
Configuration is straight forward and I just used the default setting for most everything.
If your're installing on a dedicated database server or a shared server you should obviously select the
appropriate choice. Since I'm installing on my laptop, I simply left the server type as "Developer Machine".
This setting won't offer the same performance, but it also won't use as many system resources.
I made sure to enable TCP/IP networking in order to allow the web server to connect to the database
when we get to building a web page to query the database. If you'll be running the database and web
servers on the same physical computer then you can disable this option to prevent access to the database
via the network.
Step 3 - MySQL Administrator
While it's certainly not required, I highly recommend you download and install the MySQL Administrator.
It's a great little application that provides a GUI to help you manage your new database server. While you
can get up and running using only the command line, for users who are used to using Windows
applications and wince at the thought of editing configuration files by hand or using a command prompt
it's almost a necessity. For the rest of this article, I'll assume you've installed MySQL Administrator and I'll
be using it for illustration.

Step 4 - Creating a Database

In order to create our database, we first need to connect to the server. Run MySQL Administrator and
login to your server using the password you set during installation.
You'll then want to select the "Catalogs" item at the bottom left of the MySQL Administrator window. This
should bring up a list of the current databases on the server (There should be two of them: "mysql" and
"test"). If you right-click in the small window where they are listed you should get the option to "Create
New Schema".

You'll then be prompted to enter a name for the new database. I'll be using "mydatabase" as the example
for the remainder of this article.
Once created, your new database will appear in the Schemata list along with the other databases on the
server. Selecting it from this list will bring up its details in the right hand pane.

There's not much to see because the database is still empty... so let's put something in it.

Step 5 - Creating a Table

To create a table simply click on the "Create Table" button. This brings up the following dialog box:
As you can see, I've named the table "mytable" and added 4 fields to it: an auto-incrementing primary
key id field, an integer field, a text field, and a date/time field.

When you're done making changes, you simply click the "Apply Changes" button. A window that looks
something like the one below will pop up showing you the SQL that will be executed and asking you to
confirm that you want to save changes to the table design.
At this point, we've got a database named "mydatabase" that contains a table named "mytable". Now all
we need is to add some rows of data to the table.

Step 6 - Adding Data

In the real world, data in your table would probably come in via your application. To get some sample
data into our table, I'm simply going to insert a few lines by hand. To do this I'll use the MySQL Command
Line Client. If you're still in the MySQL Administrator you can access the command line from the "Tools"
menu (Tools -> MySQL Command Line Client) otherwise you can run it from the MySQL group on the
Start Menu.

The first command in the screen above tells the server which database I want to be working in. The
second and third commands simple insert some dummy data and are the same except for the the
differences in the data being inserted.
Now we've got two sample rows of data in our table. At this point our database server is up and running
with a database, a table and even some data.

Conclusion

This article illustrated how to do the following:

 Download and install the MySQL Database Server.


 Configure the server.
 Install MySQL Administrator to make managing the database easier.
 Create a new database named "mydatabase".
 Create a new table named "mytable" in that database.
 Add a couple rows of sample data to that table.

Next time we'll look at adding users to the database server, the different options available for connecting
to your new database from .NET, and how to build a basic ASP.NET page that performs queries against
the database.

The first part of this article illustrated how to install and configure the MySQL Database Server, install and
use the MySQL Administrator, create a new database, and create and populate a new sample table with
some sample data.

Now that the database server is up and running, this part of the article will complete our coverage of using
MySQL with ASP.NET by covering how to:

 Add a new MySQL user.


 Assign the new user the appropriate permisions to the database.
 Connect to the MySQL server from .NET.
 Build a simple ASP.NET page to query the database.

Step 7 - Creating a New MySQL User Account

I'm assuming that you're been following along with part one, so at this point you should have the MySQL
Server and MySQL Adminstrator installed, and have a sample database named "mydatabase" which
contains a sample table named "mytable" with two rows of data in it.

In order to add a new user account, we'll once again need to run MySQL Administrator and login to your
server using the password you set during installation. You'll then want to select the "User Administration"
item from the list of items at the left of the MySQL Administrator window. This should bring up a list of the
current user account on the server (There should already be once called "root"). If you right-click in the
small window where the users are listed you should get the option to "Add new User".
You'll then be prompted to enter the new user's details. I've named the user "15secs" and assigned a
password of "password".
Once you've finished entering the user's details press "Apply Changes" to save your modifications.

Step 8 - Granting the User Account Access to the Database

By default new users have permission to do almost nothing. In order to allow our new user to connect to
the MySQL database server, we need to grant him what MySQL calls "Schema Privileges". This is naturally
done from the "Schema Privileges" tab in MySQL Administrator.
Notice in the above screen capture that the user has no "Assigned Privileges" to the "mydatabase"
database. Since the user will need to be able to query the database to run the sample code which follows,
I'm now going to assign the user the "SELECT" privilege by highlighting it in the "Available Privileges"
column and clicking the arrow to move it to the "Assigned Privileges" column. Once again I'll click the
"Apply Changes" button to save changes.
Depending on your application the user may very well need more permission then I've assigned to
"15secs". Most non-trivial applications will probably need at least "INSERT", "UPDATE", and "DELETE"
permissions in addition to "SELECT", but it's always best to err on the side of caution and add more
permissions as they are needed then to simply give everyone full control.

Step 9 - Connecting to the Database Server from an ASP.NET Page

To my knowledge there are currently two main ways to connect to a MySQL database server from .NET:
MySQL Connector/ODBC (aka. MyODBC) and MySQL Connector/Net. While the ODBC connector is cross-
platform and is compliant with ODBC standards, the .NET version is generally the better choice when
using MySQL with .NET.

The setup files can be downloaded from the MySQL Connector/Net page and installation is straight-
forward.
Note: Even though I selected the option to register Connector/NET in the Global
Assembly Cache and when I checked it later I found that it actually was installed there,
until I copied the MySql.Data.dll file to my application's /bin folder I couldn't get the
import statement to find the Connector/NET's namespace. The exact error message
was:

BC30466: Namespace or type specified in the Imports 'MySql.Data.MySqlClient' cannot


be found.

I'm not sure what the problem was/is, but I looked around and it seems some others are
having the same issue. So, for the time being, placing another copy of the file from it's
installed location (ie. C:\Program Files\MySQL\MySQL Connector Net 1.0.4\bin\.NET
1.1\) to your application's /bin folder (ie. C:\Inetpub\wwwroot\bin\) should resolve the
issue.

Step 10 - A Sample ASP.NET Page to Query a MySQL Database

So with our MySQL database finally squared away and MySQL Connector/Net installed, we can now start
using MySQL from our ASP.NET web pages. For illustration I'm going to provide a very simple script with
no bells and whistles. You can find fancy database scripts all over the web. The point of this one is simply
to show you what you need to do to connect to MySQL. Don't get me wrong... all that fancy stuff works
just fine using MySQL (and usually with very few changes) but that's just not the point of this script.

MySQL.aspx

<%@ Page Language="VB" debug="true" %>


<%@ Import Namespace = "System.Data" %>
<%@ Import Namespace = "MySql.Data.MySqlClient" %>
<script language="VB" runat="server">

Sub Page_Load(sender As Object, e As EventArgs)

Dim myConnection As MySqlConnection


Dim myDataAdapter As MySqlDataAdapter
Dim myDataSet As DataSet

Dim strSQL As String


Dim iRecordCount As Integer

myConnection = New MySqlConnection("server=localhost; user id=15secs; password=password;


database=mydatabase; pooling=false;")

strSQL = "SELECT * FROM mytable;"

myDataAdapter = New MySqlDataAdapter(strSQL, myConnection)


myDataSet = New Dataset()
myDataAdapter.Fill(myDataSet, "mytable")

MySQLDataGrid.DataSource = myDataSet
MySQLDataGrid.DataBind()

End Sub

</script>

<html>
<head>
<title>Simple MySQL Database Query</title>
</head>
<body>

<form runat="server">

<asp:DataGrid id="MySQLDataGrid" runat="server" />

</form>
</body>
</html>

In the above script, I've highlighted the places where the script varies from one you would use to perform
the same thing using Microsoft SQL Server or Access. As you can see there's really nothing new here.
Instead of importing System.Data.SQLClient like we would for MS SQL, we import
MySql.Data.MySqlClient. Oh and if at any point you need a reference for the MySql.Data.MySqlClient
namespace, you're in luck... it ships with one.

Here's a screen capture of what the script above produces when run against the sample database and
table we set up in this article. Like I said, it may not be pretty, but there's no reason it couldn't be. I'm
just keeping it simple for illustration.

Conclusion

In part one of this article I illustrated how to:

 Download and install the MySQL Database Server.


 Configure the server.
 Install MySQL Administrator to make managing the database easier.
 Create a new database named "mydatabase".
 Create a new table named "mytable" in that database.
 Add a couple rows of sample data to that table.

This part illustrated how to do the following:

 Add a new MySQL user.


 Assign the new user the appropriate permisions to the database.
 Connect to the MySQL server from .NET.
 Build a simple ASP.NET page to query the database.

I hope this article helped ease your introduction to this great little database server. Whether you are
upgrading from Access or starting from scratch, MySQL is certainly a viable option and despite the fact
that it's open-source and not shipped from Redmond, it really does work great with .NET. And, with the
addition of MySQL Administrator, management is no longer the source of nightmares that it used to be.
Hopefully the next time you're looking for a database server to use as the backend for your .NET
application, you'll at least consider using MySQL.

Potrebbero piacerti anche