Introduction
In a Java application, static data/information can be used in full application. Most of the "Beginner" developers like me use hard code information into code which is very dangerous for any project, especially client specific application. To prevent an unwanted disaster, we can use Java properties for static information and singleton pattern. Here, I am trying to figure out database information using Java properties and singleton pattern which can be used in full application.
Using the Code
At first, we should create a file named as db.properties, and store database information like the following:
# Static information
IP 000.000.0.00
PORT 1433
DATABASE test2
USER test2
PASS test-2
DRIVERNAME com.microsoft.sqlserver.jdbc.SQLServerDriver
JDBC jdbc:sqlserver
INSTANCE SQLEXPRESS
Now, we can use this file in singleton pattern:
import java.io.*;
import java.util.Properties;
public class DBInfo {
static private DBInfo _instance = null;
static public String port = null;
static public String database = null;
static public String ip = null;
static public String user = null;
static public String pass = null;
static public String jdbc = null;
static public String driver = null;
static public String instance = null;
protected DBInfo(){
try{
InputStream file = new FileInputStream(new File("db.properties")) ;
Properties props = new Properties();
props.load(file);
port = props.getProperty("PORT");
ip = props.getProperty("IP");
database = props.getProperty("DATABASE");
user = props.getProperty("USER");
pass = props.getProperty("PASS");
jdbc = props.getProperty("JDBC");
driver = props.getProperty("DRIVERNAME");
instance = props.getProperty("INSTANCE");
}
catch(Exception e){
System.out.println("error" + e);
}
}
static public DBInfo instance(){
if (_instance == null) {
_instance = new DBInfo();
}
return _instance;
}
}
Now, we can use this in an application:
DBInfo dbInfo = DBInfo.instance();
String connString = dbInfo.jdbc + "://" + dbInfo.ip + "\\" + dbInfo.instance +":" +
dbInfo.port + "; databaseName=" + dbInfo.database + "; userName=" +
dbInfo.user +"; passWord="+ dbInfo.pass +";";
If the client want to change IP address or database port or something else, then client can do this just by changing the db.properties file.