This week's book giveaway is in the Mac OS forum.
We're giving away four copies of a choice of "Take Control of Upgrading to Yosemite" or "Take Control of Automating Your Mac" and have Joe Kissell on-line!
See this thread for details.
The moose likes JDBC and the fly likes  connection object Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Databases » JDBC
Bookmark " connection object" Watch " connection object" New topic
Author

connection object

deepak bagdiya
Greenhorn

Joined: Sep 13, 2007
Posts: 6
Hello All,
Following are the lines from the code for getting a connection in a class:
public static Class MyDbConnect {
public static Connection dbConnect(){
InitialContext ctx = null;
Connection conn = null;
Hashtable parms = new Hashtable();
try {
parms.put(Context.INITIAL_CONTEXT_FACTORY, ---
----
javax.sql.DataSource ds = null;
ctx = new InitialContext(parms);
ds = (javax.sql.DataSource) ctx.lookup(DATASOURCE);
conn = ds.getConnection(LoginId,Passwd);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}


}
In other programs we are using the class and this method to get the connection .Something similar to following lines of code:

Class GetNames extends MyDbConnect
public Collection getResults(String Id, String name,String fname, String fid,, Connection con) throws Exception {
CallableStatement cs = null;
ResultSet rs = null;
ArrayList names = new ArrayList();
boolean local = true;
try {
if(con == null || con.isClosed())
con = getConnection();
else
local = false;
if(Id.equalsIgnoreCase("all"))
Id = null;
cs = con.prepareCall("{call SearchNames(?,?,?,?)}");
cs.setString(1, Id);
---
---
rs = cs.executeQuery();
while(rs != null && rs.next()) {
----
} catch(Exception e) {
e.printStackTrace();
} finally {
try {
if (rs != null) rs.close();
if (cs != null) cs.close();
if (local && con != null) con.close();
} catch(Exception e) {
}
}
return names;
}

Could you please advise if it is a good practice to use this type of code to get the Connection object or not .
Scott Selikoff
author
Saloon Keeper

Joined: Oct 23, 2005
Posts: 3710
    
    5

This type versus ...?


My Blog: Down Home Country Coding with Scott Selikoff
 
GeeCON Prague 2014
 
subject: connection object