KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > UseUnpooledDataSource


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 unpooled DataSource
9  */

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

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