我有一个ConnectionPool的问题,它很快就会被强化。 基本上我已经在应用程序中加载了一个监听器,只要上下文被初始化,一个Timer就会启动,并且其中的一个timertask将执行一个SQL查询,该查询使用连接池“我将连接池jar复制到Tomcat 6中“ 监听器‘只有相关的方法’:ConnectionPool从servletcontext抛出空指针
private MyTask task=new MyTask();
public void contextInitialized(ServletContextEvent event) {
this.ctx=event.getServletContext();
Timer timer= new Timer();
Calendar calendar=Calendar.getInstance();
Date firstTime=calendar.getTime();
timer.scheduleAtFixedRate(task, firstTime, 1000*60);
ctx.setAttribute("timer",timer);
}
The connection pool:
public class ConnectionPool {
private static ConnectionPool pool=null;
private static DataSource source=null;
/**
* Private constructor
* Private omdat dit klasse een singleton-patroon volgd, dus nooit meer dan een instantie is toegestaan.
*/
private ConnectionPool(){
try{
InitialContext ini=new InitialContext();
source=(DataSource)ini.lookup("java:/comp/env/jdbc/verkocht");
}catch(Exception e){
System.out.println("Verkocht db not found");//bedoelt voor test
e.printStackTrace();
}
}
/**
* Singleton getInstance() methode
* @return the connection pool
*/
public static ConnectionPool getInstance(){
if(pool==null){
pool=new ConnectionPool();
}
return pool;
}
/**
* Deze methode returneert een Connection instantie uit het pool
* @return the Connection
*/
public Connection getConnection(){
try{
return source.getConnection();
}catch(SQLException e){
System.out.println("No connection estabilished");
e.printStackTrace();
return null;
}
}
/**
* Sluid deze Connection object
* @param Een connection instantie
*/
public void freeConnection(Connection c){
try{
c.close();
} catch(SQLException e){
e.printStackTrace();
}
}
public static void main(String[] args){
ConnectionPool con=ConnectionPool.getInstance();
con.getConnection();
}
}
基本上我得到空指针在这一行:
return source.getConnection();
告诉我,数据库名称中找不到。
问题是它第一次工作5或6分钟(当我将计时器设置为1000 * 60时)查询成功发送,因此找到了数据库,这意味着上下文中的配置。 XML是正确的。
正在使用该连接池从MyTask的重写的运行方法在其内部延伸的TimerTask的方法,是:
public void assign(int toegewezenAan, double verkoopPrijs, double totaalAfgetrokken, int artikelId){
String sqlUpdate="UPDATE artikelen SET toegewezenAan=?, verkoopPrijs=?, totaalAfgetrokken=?, status=? WHERE artikelId=?";
ConnectionPool pool=ConnectionPool.getInstance();
Connection con=pool.getConnection();
PreparedStatement prep=null;
try{
prep=con.prepareStatement(sqlUpdate);
prep.setInt(1,toegewezenAan);
prep.setDouble(2, verkoopPrijs);
prep.setDouble(3,totaalAfgetrokken);
prep.setString(4, "VERKOCHT");
prep.setInt(5, artikelId);
prep.executeUpdate();
} catch(SQLException e){
e.printStackTrace();
pool.freeConnection(con);
}
}
任何意见?
请重新格式化 –