How to: Test MySQL database connectivity in ASP.NET, PHP, ASP

Simple MySQL connection test from your website with ASP.NET, PHP & classic ASP. Whenever you need a MySQL connectivity test from a website or server, it’s handy to have various test scripts nearby. Whether it is because you are setting up a new website or you have just installed a new server and are running your tests.

Nowadays, many websites depend on a MySQL or MariaDB database because CMS systems like WordPress, Joomla and Drupal are so popular, and Umbraco too. You’ll want your webserver to connect to MySQL fast and properly :)

Throughout the examples, we always use “” as our database hostname, “example_db” as databasename and username, “password” is our password.

Connect to a MySQL Database Using ASP.NET

MySql.Data.MySqlClient example

The following C# ASP.NET script tests MySQL database connectivity with MySql.Data (MySQL’s Connector/NET). All it does is: make a MySQL connection, execute one query and print the results on the screen.

As a bonus, it also prints out the .NET Framework version using System.Environment.Version.ToString().

First, verify all necessary assemblies are loaded in your web.config file:

Configure MySql.Data in your Web.config file

This assumes you are not using a system wide Connector/NET version, but your own version in the ~/bin folder.

		<compilation debug="false">
				<add assembly="MySql.Data, Version=, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>
				<add assembly="MySql.Web, Version=, Culture=neutral, PublicKeyToken=c5687fc88969c44d"/>
					<add assembly="MySql.Data.Entity, Version=, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
	<!-- [...] --->
		<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
				<assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d"/>
				<bindingRedirect oldVersion="" newVersion=""/>
				<assemblyIdentity name="MySql.Web" publicKeyToken="c5687fc88969c44d"/>
				<bindingRedirect oldVersion="" newVersion=""/>
					<assemblyIdentity name="MySql.Data.Entity" publicKeyToken="c5687fc88969c44d"/>
					<bindingRedirect oldVersion="" newVersion=""/>
	<!-- [...] --->

C# MySql.Data.MySqlClient test script

<%@ Page Language="C#" %>
<%@ Import Namespace="MySql.Data" %>
<%@ Import Namespace="MySql.Data.MySqlClient" %>

<script runat="server">
protected void Page_Load(object sender, System.EventArgs e)
void MySQLConn()
 string connStr = ";" +
   "user=example_db;database=example_db;" + 
   "port=3306;password=password;pooling=true;" +
 MySqlConnection conn = new MySqlConnection(connStr);
   Response.Write("Connecting to MySQL database...<br/>");

   string sql = "show tables";
   MySqlCommand cmd = new MySqlCommand(sql, conn);
   MySqlDataReader rdr = cmd.ExecuteReader();

   while (rdr.Read())
    Response.Write(rdr[0]+ "<br/>");

  catch (Exception ex)

 Response.Write("All done!");
 Response.Write ("<br/>.NET framework version: " + System.Environment.Version.ToString());

The above example uses an SSL connection to your MySQL database host (SslMode=REQUIRED).

Read this too:   Magento maintenance script for IIS

Tip: you may also be interested in my MySQL Connector/ODBC C# test script to use with MySQL Connector ODBC 8.0 Unicode Driver.

Connect using PowerShell

In PowerShell you can use reflection to load the MySQL.Data.dll assembly. Doing so, you can connect to MySQL using PowerShell. Neat!

$myconnection = New-Object MySql.Data.MySqlClient.MySqlConnection
$myconnection.ConnectionString = ";user id=example_db;password=password;database=example_db;pooling=true"
$mycommand = New-Object MySql.Data.MySqlClient.MySqlCommand
$mycommand.Connection = $myconnection
$mycommand.CommandText = "SHOW TABLES"
$myreader = $mycommand.ExecuteReader()

This is ideal if you want to test and debug MySQL connection issues from your PowerShell command line.

PHP MySQLi connection to MySQL

The PHP example code uses MySQLi, connects to MySQL and performs a single query when the connection is made.

 * PHP/mysqli example to connect to a MySQL database
 * Support me:

function checkMySQL() {
  $error = false;
  $connerror = false;
  @$mysqli = new mysqli( "", "example_db", "password", "example_db" );
  if ( $mysqli->connect_error ) {
    $connerror .= $mysqli->connect_error . " on";
  } else if ( $resultaat = $mysqli->query( "SHOW TABLES" ) ) {
    $error = false;
  } else {
    $error .= @$mysqli->error . " on";
  @mysqli_free_result( $resultaat );

  if ( $error !== false || $connerror !== false ) {
    echo( "Connection error:<br/> " . $connerror . ", query error:<br/>" . $error );
    return false;
  } else {
    return true;

if ( checkMySQL() ) {
    // print PHP version as bonus
    echo( "All done! PHP version: " . phpversion() );

ASP connection to a MySQL database – VBScript

The classic ASP (VbScript) code snippet uses an ADODB connection with the MySQL ODBC 5.1 Driver to connect to a MySQL database. Then it executes a single query when the connection is made.

<%@ Language=VBScript %>
 ' ASP example to connect to a MySQL database
Option Explicit
Dim sConn, sSQL, oRs, x
Set sConn = Server.CreateObject("ADODB.Connection")
sConn.Open "Provider=MSDASQL;" & _
  "Driver={MySQL ODBC 5.1 Driver};" & _
  ";" & _
  "Database=example_db;" & _
  "UID=example_db;" & _

If sConn.errors.count = 0 Then
  Response.write "Connected OK"
End If


' create the recordset object
Set oRs = Server.CreateObject("ADODB.Recordset")
' Open the recordset object executing the SQL statement
oRs.Open sSQL,sConn

If oRs.EOF Then 
  Response.Write("No records found.") 
  Do While Not oRs.EOF
    for each x in oRs.Fields
      Response.Write(x.value & "<br />")
End If

Set oRs = Nothing
Set sConn = nothing

Using SSL with MySQL and ASP

To connect to MySQL over SSL I use Connector/ODBC version 5.3.10, with the following connection string in ASP:

Read this too:   8 Tips to improve Joomla performance

' sConn.Open "DRIVER={MySQL ODBC 5.3 ANSI Driver};" &_
sConn.Open "DRIVER={MySQL ODBC 5.3 UNICODE Driver};" &_
	";" & _
	"Database=example_db;" & _
	"UID=example_db;" & _
	"PWD=password;" & _

See the ODBC connection parameters for more information.

Protip: SQL Server Compact: learn how to connect to an SqlCe database with ASP.

Perl DBI connection with MySQL (DBD::mysql)

Bonus: how to test a MySQL connection with Perl DBI. The DBI is the standard database interface module for Perl.

The DBI module enables your Perl applications to access multiple database types transparently. You can connect to PostgreSQL, SQLite, MySQL, MSSQL, Oracle, Informix, Sybase, ODBC and many more without having to know the different underlying interfaces of each. The API defined by DBI will work on all these database types and many more.

About DBI
# Yes, ^ Windows :-)
use strict;
use warnings;
use DBI;

my ($dbh, $sth);
$dbh = DBI->connect(";database=example_db", "example_db", "password", {PrintError => 0, RaiseError => 1});
my $query = "SHOW TABLES";
$sth = $dbh->prepare("$query");
$sth->execute() or die $DBI::errstr;
$dbh->disconnect ();

print "All done!"

Did this post helped you solve a problem? Or dit you find it interesting? Support Sysadmins of the North with a direct donation via Paypal of by bank wire transfer IBAN: NL31 ABNA 0432217258 (Jan Reilink). Just $ 5,- or € 5,- is more than enough, thanks!



Leave a Reply

Your email address will not be published. Required fields are marked *