KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > UseJndiDataSource


1 import java.sql.*;
2 import javax.naming.*;
3 import javax.sql.DataSource JavaDoc;
4
5 /**
6  * This example shows how to programmatically get and directly use
7  * an unpooled DataSource
8  */

9 public final class UseJndiDataSource
10 {
11
12     public static void main(String JavaDoc[] argv)
13     {
14     try
15         {
16         // let a command line arg specify the name we will
17
// lookup our DataSource.
18
String JavaDoc jndiName = argv[0];
19
20         // Create an InitialContext, and lookup the DataSource in
21
// the usual way.
22
//
23
// We are using the no-arg version of InitialContext's constructor,
24
// therefore, the jndi environment must be first set via a jndi.properties
25
// file, System properties, or by some other means.
26
InitialContext ctx = new InitialContext();
27
28         // acquire the DataSource... this is the only c3p0 specific code here
29
DataSource JavaDoc ds = (DataSource JavaDoc) ctx.lookup( jndiName );
30
31         // get hold of a Connection an do stuff, in the usual way
32
Connection con = null;
33         Statement stmt = null;
34         ResultSet rs = null;
35         try
36             {
37             con = ds.getConnection();
38             stmt = con.createStatement();
39             rs = stmt.executeQuery("SELECT * FROM foo");
40             while (rs.next())
41                 System.out.println( rs.getString(1) );
42             }
43         finally
44             {
45             // i try to be neurotic about ResourceManagement,
46
// explicitly closing each resource
47
// but if you are in the habit of only closing
48
// parent resources (e.g. the Connection) and
49
// letting them close their children, all
50
// c3p0 DataSources will properly deal.
51
attemptClose(rs);
52             attemptClose(stmt);
53             attemptClose(con);
54             }
55         }
56     catch (Exception JavaDoc e)
57         { e.printStackTrace(); }
58     }
59
60     static void attemptClose(ResultSet o)
61     {
62     try
63         { if (o != null) o.close();}
64     catch (Exception JavaDoc e)
65         { e.printStackTrace();}
66     }
67
68     static void attemptClose(Statement o)
69     {
70     try
71         { if (o != null) o.close();}
72     catch (Exception JavaDoc e)
73         { e.printStackTrace();}
74     }
75
76     static void attemptClose(Connection o)
77     {
78     try
79         { if (o != null) o.close();}
80     catch (Exception JavaDoc e)
81         { e.printStackTrace();}
82     }
83
84     private UseJndiDataSource()
85     {}
86 }
87
Popular Tags