Connection conn=null;
public String db_conn_string;
public String db_conn_user;
public String db_conn_pass;
public Properties ruleProp=null;
PreparedStatement ps = null;
ResultSet rs = null;
public DB_Manager(){
setConnectionProperties();
}
public Connection getDBConnection(String strConnectString,String db_uname,String db_password){
try {
Class.forName ("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(strConnectString, db_uname, db_password);
}
catch(Exception e) {
e.printStackTrace();
}
return conn;
}
public void setConnectionProperties(){
Properties prop = new Properties();
String path="";
try {
path = new java.io.File("/").getAbsolutePath();
prop.load(new FileInputStream(path+"data/portals/RN_Member.war/WEB-INF/properties/rule.properties")); // Set your property file path
db_conn_string = prop.getProperty("DB_CONNECTSTRING");
db_conn_user = prop.getProperty("DB_USERNAME");
db_conn_pass = prop.getProperty("DB_PASSWORD");
} catch (Exception e) {
e.printStackTrace();
}
}
public void getFreeDBConnection(Connection conn){
try{
if (conn!=null) conn.close();
}catch(Exception e){
e.printStackTrace();
}
}
/*
call the following execute query which will open the connection execute the query and will return the java multi dimentional array and close the DB connection within itself.
*/
public String[][] executeQuery(String sql){
String[][] results=null;
try{
conn = getDBConnection(db_conn_string,db_conn_user,db_conn_pass);
ps = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); //to move to last and first
rs = ps.executeQuery();
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
int numRows = 0;
if(rs.last()){ // to get the row counts
numRows = rs.getRow();
rs.first();
}
results = new String[numRows][numCols];
//System.out.println(numRows+"-"+numCols);
int n = 0;
int p = 0;
for(int k=0; k < numRows; k++){
p = 0;
for(int m=1;m<=numCols;m++){
results[n][p] = rs.getString(m) ;
p++;
}
n++;
rs.next();
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{ps.close();}catch(Exception e){};
try{rs.close();}catch(Exception e){};
getFreeDBConnection(conn);
}
if(results.length==0){
int intFields = getFieldCounts(sql, ",")+1;
results = new String[1][intFields];
for(int n=0; n < intFields;n++){
results[0][n]="0";
}
}
return results;
}
}
Sampe property file for DB Connection:
# DB Connection
DB_CONNECTSTRING=jdbc:oracle:oci:@147.120.111.131:1521:r5dev11
DB_USERNAME=system
DB_PASSWORD=oracle
Sign up here with your email