Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

Dynamic loading of JDBC (Database) Connection Properties in Java

Program to demonstrate how to load JDBC Connection properties in Java dynamically.

1. Create JDBC Database Connection Properties file for MySql (connection.properties)

# Database Properties

database.driver=com.mysql.jdbc.Driver
database.url=jdbc:mysql://localhost:3306/sample
database.user=root
database.password=root


2. Create a Java class for loading of this properties.
package com.hubberspot.example;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class DatabaseConnection {

 public static void main(String[] args) throws IOException {
 
  File propertiesFile = new File("F:/Java/Spring/workspace/Java/src/connection.properties");
  FileReader fileReader = new FileReader(propertiesFile);
  
  Properties props = new Properties();
  props.load(fileReader);
  
  String driver = props.getProperty("database.driver");
  String url = props.getProperty("database.url");
  String user = props.getProperty("database.user");
  String password = props.getProperty("database.password");
  
  System.out.println("Driver : " + driver);
  System.out.println("Url : " + url);
  System.out.println("User : " + user);
  System.out.println("Password : " + password);

 }
 
}



Output of the program :



In future, if you wish to change the database say from MySql to Oracle, than just you need to change connection.properties file.See below :

1. Create JDBC Database Connection Properties file for Oracle (connection.properties)

# Database Properties

database.driver=oracle.jdbc.driver.OracleDriver
database.url=jdbc:oracle:thin:@localhost:1521:sample
database.user=root
database.password=root


After running the above Java class again we get the output as :

Output of the program : 

 


 
© 2021 Learn Java by Examples Template by Hubberspot