Showing posts with label Connecting Java and MySQL. Show all posts
Showing posts with label Connecting Java and MySQL. Show all posts

Wednesday, 12 February 2014

Connecting Java and MySQL in Eclipse

In order to Connect to a database, java needs an interface. Therefore, JDBC (Java database connectivity) serves the purpose of establishing a connection between the database and Java.


Once this is set, we can create a class that will provide us with the database connection:


package database;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBConnection
{
private static String driver = "com.mysql.jdbc.Driver";

private static String url = "jdbc:mysql://localhost:3306/";

private static String dbname = "myDBName";

private static DBConnection instance = null;

private static Connection conn = null;

private DBConnection()
{
}

public static DBConnection getInstance()
{
if (instance == null)
{
instance = new DBConnection();
}
return instance;
}

public Connection getConnection()
{
if (conn != null) return conn;
try
{
Class.forName(driver).newInstance();
}
catch (java.lang.ClassNotFoundException e)
{
System.out.println("ClassNotFoundException: " + e.getMessage());
e.printStackTrace();
}
catch (InstantiationException e)
{
System.out.println("InstantiationException: " + e.getMessage());
e.printStackTrace();
}
catch (IllegalAccessException e)
{
System.out.println("IllegalAccessException: " + e.getMessage());
e.printStackTrace();
}
System.out.println("MySQL JDBC Driver Registered!");
try
{
conn = DriverManager.getConnection(url + dbname, "root", "root");
}
catch (SQLException ex)
{
// handle any errors
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
}
if (conn != null)
{
System.out.println("connection established");
}
else
{
System.out.println("Failed to make database connection!");
}
return conn;
}

}


Write a driver to test the DBConnection class:


public class DBConnectionDriver 
{

public void DBConnectionDriver()
{
DBConnection dbConn = DBConnection.getInstance();
Connection conn = dbConn.getConnection();
try
{
if (conn != null) conn.close(); // Perform any task
}
catch (SQLException e1)
{
System.out.println("SQLException: " + e1.getMessage());
e1.printStackTrace();
}
}

}