Pin It

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 : 

 


Please Give Us Your 1 Minute In Sharing This Post!
SOCIALIZE IT →
FOLLOW US →
SHARE IT →
Related Posts Plugin for WordPress, Blogger...

Post your related queries below ...

comments powered by Disqus
Powered by Blogger.
 
© 2012 Learn Java by Examples Template by Hubber Spot