Different way to establish Database Connection with MySQL database

Here I am explaing how to establish database connection in different way. The Class.forName() is not required to load the driver, there are other way also or it is optional. Only thing that add the respective database driver file in the class, The DriverManager.getConnection() automatically load the driver accordingly.

Before running the below code, you add the MySQL Connection jar file in the classpath

Way -1 : Establish database connection using Class.forName() method for MySQL.

public Connection connection1() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test?user=root&password=root");
System.out.println(con);
return con;
}

Way - 2: Establish database connection using system property jdbc.driver for MySQL.

public Connection connection2() throws Exception {
// set the jdbc.drivers in system property and establish the connection
// System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test?user=root&password=root");
System.out.println(con);
return con;
}


Way 3 :Establish database connection using Drivermanager.registerDriver() method for MySQL.

public Connection connection3() throws Exception
{
Driver driver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver( driver );
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/test?user=root&password=root");
System.out.println(con);
return con;
}

Way 4 :Establish database connection using properties file for MySQL. You can change the database connection propeties in propperties file and program will be connected accordingly without changing the source code.

Create src\pkg1\DbConnection.properties file as below -

dbname=test
username=root
password=root
dbserver=localhost
driver=jdbc:mysql:

Java source code is below -

public Connection connection4() throws Exception {
Properties p1=new Properties();
p1.load(new FileInputStream("srcpkg1DbConnection.properties"));
Connection con=DriverManager.getConnection(p1.getProperty("driver")+"//"+p1.getProperty("dbserver")+"/"+p1.getProperty("dbname")+"?user="+p1.getProperty("username")+"&password="+p1.getProperty("password"));
System.out.println(con);
return con;
}

Previous Next


Write your Comment

Name :
Email Id : [ We will not publish your email id ]
Your Comment : [ Maximum 200 chars ]
Enter Security code