I am trying to solve this problem with the help of properties file, but in a Properties file, we can handle only Database Driver problem. If I want to switch my MySQL to Oracle database I need to change my all query. The problem is how to make query independent in JDBC?
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
public class DBIndependencyExample {
public static void main(String[] args) {
try {
Properties pros = new Properties();
InputStream fis = new FileInputStream(
"D:\Programs\Eclipse\DBIndependecyByPropertiesFile\src\connectdb.properties");
pros.load(fis);
String Drivername = pros.getProperty("k1");
//System.out.println(Drivername);
String url = pros.getProperty("k2");
String un = pros.getProperty("k3");
String pw = pros.getProperty("k4");
Class.forName(Drivername);
Connection con = DriverManager.getConnection(url, un, pw);
System.out.println("Driver Is Loaded With" + Drivername);
System.out.println("Connection is Opened");
Statement smt = con.createStatement();
String sql = pros.getProperty("k5");
//System.out.println(sql);
ResultSet rs = smt.executeQuery(sql);
while (rs.next()) {
System.out.println("username is:" + rs.getString(1) + " password is:" + rs.getString(2));
}
con.close();
System.out.println("Connection is closed");
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Properties File:
//Mysql Connectivity
//Start Properties File Code
k1=com.mysql.jdbc.Driver
k2=jdbc:mysql://localhost:3306/practice
k3=root
k4=root
k5=select * from student
//Oracle Connectivity
k1=oracle.jdbc.driver.OracleDriver
k2=jdbc:oracle:thin:@localhost:1521/orcla
k3=scott
k4=manish
k5=select * from dept
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…