Connecting to a MySQL Database Using ASP.NET
- Knowledge of computer programming.
- Microsoft® Visual Studio .NET.
- MySql Connector/NET on your development computer. For more information, click here.
- Knowledge of MySql and specifically the MySql.Data Namespace.
- A setup MySql Database. For more information, see Creating MySQL or SQL Server Databases for Your Hosting Account.
To Connect to a MySQL Database Using ASP.NET
- Find your database's connection strings. For more information, see Locating Your Database Connection Strings.
NOTE:Change the your password value to your real database password value.
- Using Microsoft Visual Studio .NET create an ASP.NET Project.
- Add a reference to MySql.Data.dll.
- Replace the value in the following code with
your_ConnectionStringwith your database information.
- Insert the following code into your project including your modified
NOTE: If your MySql database was created with the Allow Direct Database Access enabled, you can connect to the database from your development computer. If you did not enable Allow Direct Database Access, your MySql is in a secure environment and you cannot connect to the database from your development computer. A connection can only be successful when your code is deployed to the hosting site.
MySql.Data.MySqlClient.MySqlConnection mySqlConnection = new
mySqlConnection.ConnectionString = “your_ConnectionString”;
// Connection has been made
// Connection could not be made, throw an error
throw new Exception("The database connection state is Closed");
// Connection is actively doing something else
// Place Your Code Here to Process Data //
catch (MySql.Data.MySqlClient.MySqlException mySqlException)
// Use the mySqlException object to handle specific MySql errors
catch (Exception exception)
// Use the exception object to handle all other non-MySql specific errors
// Make sure to only close connections that are not in a closed state
if (mySqlConnection.State != System.Data.ConnectionState.Closed)
// Close the connection as a good Garbage Collecting practice
What are the new features available in MySQL 4.1?
How many simultaneous connections can one MySQL database have?
What are the major differences between MySQL 4.0 and 4.1/5.0?
Which MySQL features do you disable on hosting accounts?
How do I recompile the MySQL library to run under medium trust?
How do you limit MySQL databases?
Your message was successfully sent.