Connecting to mysql database
Below is the code for creating mysql connection in java and php.
Please make sure that mysql-connector-java-5.0.6-bin.jar is in class path.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class MySqlConnectionTest {
public static void main(String[] args) {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
// We want to connect to a database name 'test' in mysql.
connection = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/test", "root", "root");
if (!connection.isClosed()) {
System.out.println("Successfully connected to MySQL server...");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
}
}
}
}
Below is the code in php for mysql connection.
<?php
$hostname='localhost'; //// specify host
$user='root'; //// database user name
$password='root'; //// database password
$database='test'; //// database name
$connection = mysql_connect("$hostname" , "$user" , "$passwprd")
or die ("Unable connect to MySQL");
$db = mysql_select_db($database , $connection) or die ("Can't find database.");
?>
Related Post
Comments
Leave a Reply