KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > JndiBindDataSource


1 import java.sql.*;
2 import javax.naming.*;
3 import javax.sql.DataSource JavaDoc;
4 import com.mchange.v2.c3p0.DataSources;
5
6
7 /**
8  * This example shows how to acquire a c3p0 DataSource and
9  * bind it to a JNDI name service.
10  */

11 public final class JndiBindDataSource
12 {
13     // be sure to load your database driver class, either via
14
// Class.forName() [as shown below] or externally (e.g. by
15
// using -Djdbc.drivers when starting your JVM).
16
static
17     {
18     try
19         { Class.forName( "org.postgresql.Driver" ); }
20     catch (Exception JavaDoc e)
21         { e.printStackTrace(); }
22     }
23
24     public static void main(String JavaDoc[] argv)
25     {
26     try
27         {
28         // let a command line arg specify the name we will
29
// bind our DataSource to.
30
String JavaDoc jndiName = argv[0];
31
32         // acquire the DataSource using default pool params...
33
// this is the only c3p0 specific code here
34
DataSource JavaDoc unpooled = DataSources.unpooledDataSource("jdbc:postgresql://localhost/test",
35                                      "swaldman",
36                                      "test");
37         DataSource JavaDoc pooled = DataSources.pooledDataSource( unpooled );
38
39         // Create an InitialContext, and bind the DataSource to it in
40
// the usual way.
41
//
42
// We are using the no-arg version of InitialContext's constructor,
43
// therefore, the jndi environment must be first set via a jndi.properties
44
// file, System properties, or by some other means.
45
InitialContext ctx = new InitialContext();
46         ctx.rebind( jndiName, pooled );
47         System.out.println("DataSource bound to nameservice under the name \"" +
48                    jndiName + '\"');
49         }
50     catch (Exception JavaDoc e)
51         { e.printStackTrace(); }
52     }
53
54     static void attemptClose(ResultSet o)
55     {
56     try
57         { if (o != null) o.close();}
58     catch (Exception JavaDoc e)
59         { e.printStackTrace();}
60     }
61
62     static void attemptClose(Statement o)
63     {
64     try
65         { if (o != null) o.close();}
66     catch (Exception JavaDoc e)
67         { e.printStackTrace();}
68     }
69
70     static void attemptClose(Connection o)
71     {
72     try
73         { if (o != null) o.close();}
74     catch (Exception JavaDoc e)
75         { e.printStackTrace();}
76     }
77
78     private JndiBindDataSource()
79     {}
80 }
81
Popular Tags