Files
gateway-mnp-dbc/dbcmnpsrc/FE/mnpdev/sim/InfobusR4/src/tim/dao/BaseDao.java
2024-05-13 12:54:14 +02:00

111 lines
2.0 KiB
Java

package tim.dao;
import java.sql.*;
import javax.naming.*;
import javax.sql.*;
/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2007</p>
* <p>Company: </p>
* @author not attributable
* @version 1.0
*/
public abstract class BaseDao {
protected DataSource ds;
protected InitialContext ctx;
protected String DATASOURCE = "jdbc/mnpDS";
/**
* Inizializza il data source
* @throws Exception
*/
protected void initDB() throws Exception{
try
{
ctx = new InitialContext();
ds = (DataSource)ctx.lookup(DATASOURCE);
}
catch (Exception ex)
{
ex.printStackTrace();
throw ex;
}
finally
{
try
{
ctx.close();
}
catch (Exception ex) {}
}
}
/**
* Metodo per ottenere le connessioni dal DB
* Se non è disponibile una connessione ritorna null
*/
public Connection getConnection() throws Exception{
Connection conn = null;
try
{
if (ds==null) initDB();
conn = ds.getConnection();
}
catch (Exception ex)
{
ex.printStackTrace();
throw ex;
}
finally
{
try
{
if( conn != null ) conn.setAutoCommit(false);
}
catch (Exception ex)
{
ex.printStackTrace();
throw ex;
}
}
// se non riesce ad ottenere una connessione per tre volte torna null
return conn;
}
/**
* Metodo per la chiusura del ResultSet,dello Statement e della Connection
* tale metodo non lancia eccezzioni
* @param rs
* @param stmt
* @param c
*/
public void closeAll(ResultSet rs, Statement stmt, Connection c) {
try
{
if(rs!=null) rs.close();
}
catch (Throwable ex) {}
try
{
if(stmt!=null) stmt.close();
}
catch (Throwable ex) {}
try
{
if(c!=null)
c.close();
}
catch (Throwable ex) {}
}
}