1 package com.netpotlet.test;
2
3 import java.sql.Connection;
4 import java.sql.SQLException;
5
6 import javax.sql.DataSource;
7
8 import org.apache.commons.dbcp.ConnectionFactory;
9 import org.apache.commons.dbcp.DriverManagerConnectionFactory;
10 import org.apache.commons.dbcp.PoolableConnectionFactory;
11 import org.apache.commons.dbcp.PoolingDataSource;
12 import org.apache.commons.pool.ObjectPool;
13 import org.apache.commons.pool.impl.StackObjectPool;
14
15 public class ConnectionManager {
16 private static ConnectionManager manager = null;
17 private DataSource dataSource = null;
18
19 public static ConnectionManager
20 getInstance(String drivername,
21 String
url,
22 String
username,
23 String
password)
24 throws ClassNotFoundException,
RuntimeException {
25 if (manager == null) {
26 manager
=
27 new
ConnectionManager(drivername,
28 url,
29 username,
30 password);
31 }
32 return manager;
33 }
34
35 private ConnectionManager(String drivername,
36 String
url,
37 String
username,
38 String
password)
39 throws ClassNotFoundException,
RuntimeException {
40 Class.forName(drivername);
41 ObjectPool pool = new StackObjectPool();
42 ConnectionFactory factory
=
43 new
DriverManagerConnectionFactory(url,
44 username,
45 password);
46 try {
47 new
PoolableConnectionFactory(
48 factory,
49 pool,
50 null,
51 null,
52 false,
53 true);
54 dataSource
= new PoolingDataSource(pool);
55 } catch (Exception e) {
56 throw
new RuntimeException(e);
57 }
58 }
59
60 Connection getConnection() throws SQLException {
61 synchronized (dataSource)
{
62 return
dataSource.getConnection();
63 }
64 }
65
66 void returnConnection(Connection connection) throws
SQLException {
67 if (connection != null) {
68 connection.close();
69 }
70 }
71 }