asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search





Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology
International

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

A Step-by-Step Guide To Using MySQL with ASP.NET - Part 2
By Ziran Sun
Rating: 4.3 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article

    Introduction

    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.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Supporting Products/Tools
    Proposion N2N
    Proposion N2N connects Microsoft .NET applications to Lotus Notes and Lotus Domino databases. This ADO.NET managed data provider allows you to perform blindingly fast queries and updates of Notes data from ASP.NET pages, .NET web services, Windows, or Mobile applications. An innovative SQL-like query language leverages the unique features of Notes and makes collaborative software accessible to relational database programmers.
    [Top]
    Other Articles
    Sep 15, 2005 - Building an Image Keyword System
    Unlike text-based file formats image files aren't made up of words, which makes searching for an image file by keyword difficult. Instead of being able to simply open the file to see what it contains, we're stuck looking at the text around it and other metadata to determine the image's meaning. In this article, Ziran Sun shows you how to build a simple database-based image keyword system that allows you to associate keywords with images and use these keywords to make finding images easier.
    [Read This Article]  [Top]
    Feb 10, 2005 - A Step-by-Step Guide To Using MySQL with ASP.NET - Part 1
    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.
    [Read This Article]  [Top]
    Jan 27, 2005 - Moving a Database from SQL Server 7.0 to SQL Server 2000
    Moving or copying a SQL Server database from one machine to another requires a lot of preparation in order to ensure a smooth transfer. In this article, Dina Fleet Berry examines the different methods and highlights the different issues associated with each of them.
    [Read This Article]  [Top]
    Jan 6, 2005 - Debugging a SQL Stored Procedure from inside SQL Server 2000 Query Analyzer
    There are many times when using SQL Server 2000 Query Analyzer to debug SQL statements is a better choice than debugging in Visual Studio .NET. In this article, Dina Fleet Berry explains why and walks you through the debugging process step-by step.
    [Read This Article]  [Top]
    Nov 24, 2004 - Persisting .NET Objects to SQL Server Using SQLXML and Serialization
    As a follow up to his article on retrieving objects from SQL Server using SQLXML and serialization, Gianluca Nuzzo discusses saving objects back to SQL Server using a schema definition file and updategrams.
    [Read This Article]  [Top]
    Sep 14, 2004 - Transaction Processing in ADO.NET 2.0
    One area that stands out when comparing ADO.NET 1.x to ADO.NET 2.0 is transaction processing. Bill Ryan shows just how easy transaction processing has become with the TransactionScope object in ADO.NET 2.0.
    [Read This Article]  [Top]
    Sep 8, 2004 - Custom Object Data Binding with .NET
    Developers often use brute force coding to marshal data between the GUI and application objects. In this article, Luther Stanton explains how to use .NET's out-of-the box data-binding functionality to make this job much easier.
    [Read This Article]  [Top]
    Sep 2, 2004 - Queue MSMQ Messages from SQL Server
    Learn how to create a console application to queue a message in Microsoft Message Queuing (MSMQ) and then use an extended stored procedure to call the console application from a SQL Server trigger.
    [Read This Article]  [Top]
    Aug 30, 2004 - Tuning Up ADO.NET Connection Pooling in ASP.NET Applications
    Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. This article shows how to monitor the connection pool, diagnose a potential problem, and apply the appropriate fix.
    [Read This Article]  [Top]
    Jul 13, 2004 - Retrieving Objects from SQL Server Using SQLXML and Serialization
    This article will describe how to design a data access layer for a set of entities. You'll learn how to write an XSD schema and design two simple helper classes -- one for reading an XML stream from SQL Server using SQLXML and another for deserializing the XML stream.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry



    JupiterOnlineMedia

    internet.comearthweb.comDevx.commediabistro.comGraphics.com

    Search:

    Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

    Jupitermedia Corporate Info


    Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

    Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers