How to establish a connection with the database using the properties file in JDBC?


One of the variant of the getConnection() method of the DriverManager class accepts url of the database, (String format) a properties file and establishes connection with the database.

Connection con = DriverManager.getConnection(url, properties);

To establish a connection with a database using this method −

Set the Driver class name as a system property −

System.setProperty("Jdbc.drivers", "com.mysql.jdbc.Driver");

Create a properties object as −

Properties properties = new Properties();

Add the user name and password to the above created Properties object as −

properties.put("user", "root");
properties.put("password", "password");

Finally invoke the getConnection() method of the DriverManager class by passing the URL and, properties object as parameters.

//Getting the connection
String url = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(url, properties);

Following JDBC program establishes connection with the MYSQL database using a properties file.

Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class EstablishingConnectionUsingProperties {
   public static void main(String args[]) throws SQLException {
      //Registering the Driver
      System.setProperty("Jdbc.drivers", "com.mysql.jdbc.Driver");
      Properties properties = new Properties();
      properties.put("user", "root");
      properties.put("password", "password");
      //Getting the connection
      String url = "jdbc:mysql://localhost/mydatabase";
      Connection con = DriverManager.getConnection(url, properties);
      System.out.println("Connection established: "+ con);
   }
}

Output

Connection established: com.mysql.jdbc.JDBC4Connection@2db0f6b2

Rishi Raj
Rishi Raj

I am a coder

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements