Whenever you need to test the MySQL database connectivity from a ASP.NET website, whether it is because you are setting up a new website or you have just installed a new server and are running your tests, it’s handy to have a MySql.Data C# code first test script nearby.
You may find more information about MySQL connectivity from ASP.NET in my post ASP and ASP.NET connectionstring examples for Microsoft SQL Server and MySQL. Enjoy! 🙂
MySql.Data.MySqlClient example test script
Eventhough all installations are done unattended, I use the following C# ASP.NET script to test MySQL database connectivity with MySql.Data (MySQL’s Connector/NET). Just to be sure. All it does is making a connection, execute one query and print the results on the screen.
<%@ Page Language="C#" %>
<%@ Import Namespace="MySql.Data" %>
<%@ Import Namespace="MySql.Data.MySqlClient" %>
<script runat="server">
protected void Page_Load(object sender, System.EventArgs e)
{
MySQLConn();
}
void MySQLConn()
{
string connStr = "server=mysql.example.com;" +
"user=example_db;database=example_db;" +
"port=3306;password=password;pooling=true;";
MySqlConnection conn = new MySqlConnection(connStr);
try
{
Response.Write("Connecting to MySQL database...<br/>");
conn.Open();
string sql = "show tables";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
Response.Write(rdr[0]+ "<br/>");
}
rdr.Close();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
conn.Close();
Response.Write("Done.");
Response.Write ("<br/>.NET framework version: " + System.Environment.Version.ToString());
}
</script>
As a bonus, it also prints out the .NET Framework version using System.Environment.Version.ToString().
MySQL Connector/NET, Entity Framework in partial trust
When you run in to problems setting up MySQL Connector/NET, with or without Entity Framework, in a partial trust environment, check and re-check your web.config settings. Most problems and Exceptions are the result of tiny configuration errors in your web.config file. I’ve described some commonly made mistakes on Saotn.org in the post MySQL Connector/NET and EntityFramework. The post also links to posts how to install and set up MySQL Connector/NET in a partial trust environment.
Summary
- Use a MySql.Data C# test script to verify MySQL database connectivity from an ASP.NET website.
- The script connects to MySQL, executes a query, and displays the .NET Framework version.
- When facing issues with MySQL Connector/NET in partial trust, check your web.config settings for errors.
- Refer to related posts on Saotn.org for common mistakes and setup guidance with MySQL Connector/NET.