- To connect to MySQL, make sure you have downloaded the MySQL Connector/j.
- Once the Connector/j is downloaded we have to include it in the projects build path.
- Eclipse:adding jars to project build path
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();
}
}
}
No comments:
Post a Comment