Sample JDBC coding

Post date: Mar 08, 2012 10:40:15 PM

public class MyDBConnection {

private Connection conn;

private Stack stack = null;

private long createTime = 0;

private int connNumber = 0;

/* contructor to make a connection to a database */

public MyDBConnection(String driverName, String JDBCURL, String isolation, String lockWait) throws Exception {

loadDriver(driverName);

getNewConnection(JDBCURL, isolation, lockWait);

createTime = System.currentTimeMillis();

connNumber = 0;

}

public MyDBConnection(String driverName, String JDBCURL, String isolation, String lockWait, int connectionNumber)

throws Exception {

loadDriver(driverName);

getNewConnection(JDBCURL, isolation, lockWait);

createTime = System.currentTimeMillis();

connNumber = connectionNumber;

}

public void loadDriver(String driverName) throws Exception {

Class.forName(driverName).newInstance();

}

public void getNewConnection(String JDBCURL, String isolation, String lockWait) throws Exception {

conn = DriverManager.getConnection(JDBCURL);

reset(isolation, lockWait);

}

public void close() {

try {

conn.close();

} catch(Exception e) {}

}

public Statement createStatement() throws Exception {

return conn.createStatement();

}

public PreparedStatement prepareStatement( String sql ) throws Exception {

return conn.prepareStatement( sql );

}

public void begin(String routine) throws Exception {

stack.push(routine);

conn.setAutoCommit(false);

}

public void commit() throws Exception {

if(!stack.empty())

stack.pop();

if(stack.empty()) {

if(!conn.getAutoCommit()){

conn.commit();

conn.setAutoCommit(true);

}

}

}

public void rollback() {

try {

if(!stack.empty())

stack.pop();

if(stack.empty()) {

if(!conn.getAutoCommit()){

conn.rollback();

conn.setAutoCommit(true);

}

}

} catch (Exception e) {}

}

stmt.close();

stack = new Stack();

conn.setAutoCommit(true);

}

public void setAutoCommit(boolean autoCommit) throws SQLException {

conn.setAutoCommit(autoCommit);

}

public boolean getAutoCommit() throws SQLException{

return conn.getAutoCommit();

}