KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > UsePoolBackedDataSource


1 import java.sql.*;
2 import javax.sql.DataSource JavaDoc;
3 import com.mchange.v2.c3p0.DataSources;
4
5
6 /**
7  * This example shows how to programmatically get and directly use
8  * an pool-backed DataSource
9  */

10 public final class UsePoolBackedDataSource
11 {
12
13     public static void main(String JavaDoc[] argv)
14     {
15     try
16         {
17         // Note: your JDBC driver must be loaded [via Class.forName( ... ) or -Djdbc.properties]
18
// prior to acquiring your DataSource!
19

20         // Acquire the DataSource... this is the only c3p0 specific code here
21
DataSource JavaDoc unpooled = DataSources.unpooledDataSource("jdbc:postgresql://localhost/test",
22                                      "swaldman",
23                                      "test");
24         DataSource JavaDoc pooled = DataSources.pooledDataSource( unpooled );
25
26
27
28         // get hold of a Connection an do stuff, in the usual way
29
Connection con = null;
30         Statement stmt = null;
31         ResultSet rs = null;
32         try
33             {
34             con = pooled.getConnection();
35             stmt = con.createStatement();
36             rs = stmt.executeQuery("SELECT * FROM foo");
37             while (rs.next())
38                 System.out.println( rs.getString(1) );
39             }
40         finally
41             {
42             //i try to be neurotic about ResourceManagement,
43
//explicitly closing each resource
44
//but if you are in the habit of only closing
45
//parent resources (e.g. the Connection) and
46
//letting them close their children, all
47
//c3p0 DataSources will properly deal.
48
attemptClose(rs);
49             attemptClose(stmt);
50             attemptClose(con);
51             }
52         }
53     catch (Exception JavaDoc e)
54         { e.printStackTrace(); }
55     }
56
57     static void attemptClose(ResultSet o)
58     {
59     try
60         { if (o != null) o.close();}
61     catch (Exception JavaDoc e)
62         { e.printStackTrace();}
63     }
64
65     static void attemptClose(Statement o)
66     {
67     try
68         { if (o != null) o.close();}
69     catch (Exception JavaDoc e)
70         { e.printStackTrace();}
71     }
72
73     static void attemptClose(Connection o)
74     {
75     try
76         { if (o != null) o.close();}
77     catch (Exception JavaDoc e)
78         { e.printStackTrace();}
79     }
80
81     private UsePoolBackedDataSource()
82     {}
83 }
84
Popular Tags