hostmysite.com

How do I use a connection string to connect to a MySQL database?

Please note: This support article is a guide for our Linux users only.


The following article explains how to use a connection string to connect to a MySQL database. The syntax of the connection string will vary based on the programming language you are using. Below are sample connection strings for PHP, ColdFusion, Perl and JSP. The code snippets can be added directly to your code.

In the following examples, please substitute your information where the following data is referenced:

PHP

<?php
$link = mysql_connect('<server>', '<username>', '<password>');
if (!$link) {
  die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_select_db(<database>);
?>

ColdFusion

<CFQUERY Name="test" DATASOURCE="<DSN>" USERNAME="<username>" PASSWORD="<password>">
</CFQUERY>

Perl

#!/usr/bin/perl

use DBI;

$db = DBI->connect("dbi:mysql:<database>","<username>","<password>")
or die("Couldn't connect");

$db->disconnect;

JSP

<%@ page import="java.sql.*" %>
<%@ page import="com.mysql.jdbc.Driver" %>

<%!
Class.forName("com.mysql.jdbc.Driver").newInstance();
java.sql.Connection conn;
conn = DriverManager.getConnection(
"jdbc:mysql://<server>/<database>?user=<username>&password=<password>");
%>

Additional Support Topics

Search Support Articles