How do I connect to my MySQL database with PHP, Perl, C#, VB.Net or Classic ASP?

Connecting to your MySQL database with any one of these languages is very simple! Below we will give some very simple code samples in the above languages to get you started! These are basic code samples that do not include any error or exception handling as this should be implemented to meet each applications logging / exception handling requirements.

PHP – MySQL


PHP - MySQLi (Procedural)

1
2
3
4
5
6
7
8
<!--?php
$myConn = mysqli_connect('myServerHost', 'myUsername', 'myPassword', 'myDatabase');
mysqli_close($myConn);
</pre-->
<p><strong>PHP - MySQLi (OO)</strong></p>
<pre lang="php" line="1"><!--?php
$myConn = new mysqli('myServerHost', 'myUsername', 'myPassword', 'myDatabase');
$myConn--->Close();

PHP - PDO

1
2
3
4
5
6
7
8
9
10
<!--?php
$myConn = new PDO('mysql:host=myServerHost;dbname=myDatabase', 'myUsername', 'myPassword');
$myConn = null;
</pre-->
<p><strong>Perl</strong></p>
<pre lang="perl" line="1">use DBI;
use DBD::mysql;
 
$myConn = DBI-&gt;connect("dbi:mysql:myDatabase;myServerHost", "myUser", "myPassword");
$myConn-&gt;disconnect

C# - MySQL .Net Connector

1
2
3
4
5
using MySql.Data.MySqlClient;
 
MySqlConnection myConn = new MySqlConnection("Server=myServerHost;Database=myDatabase;Uid=myUsername;Pwd=myPassword");
myConn.Close();
myConn.Dispose();

VB.Net - MySQL .Net Connector

1
2
3
4
5
6
7
Imports MySql.Data.MySqlClient
 
dim myConn As MySqlConnection
myConn = new MySqlConnection("Server=myServerHost;Database=myDatabase;Uid=myUsername;Pwd=myPassword")
 
myConn.Close()
myConn.Dispose()

Classic ASP (MyODBC 5.1)

1
2
3
4
5
6
7
8
9
10
&lt;%
Dim sConnection, objConn , objRS
 
sConnection = "DRIVER={MySQL ODBC 5.1 Driver}; SERVER=myServerHost; DATABASE=myDatabase; UID=myUsername;PASSWORD=myPassword; OPTION=3"
Set objConn = Server.CreateObject("ADODB.Connection")
objConn.Open(sConnection)
 
objConn.Close
Set objConn = Nothing
%&gt;