Data | Data source JSP development call Tomcat database connection pool, perhaps a lot of friends will, the following code is believed to have used people are familiar with:
list1:testpool.jsp
<%
InitialContext ctx=new InitialContext ();
DataSource ds = (DataSource) ctx.lookup ("Java:comp/env/jdbc/mysql");
Connection conn = Ds.getconnection ();
Statement stmt = Conn.createstatement ();
String strSQL = "SELECT * from T_user";
ResultSet rs = stmt.executequery (strSQL);
......
Stmt.close ();
Rs.close ();
Conn.close ();
%>
But many people do not know that when Tomcat was started, the data source was bound with Jndi, so it was not known how to use the main function in J2SE to call the data source, in fact, as long as the testpool.jsp to do a little change:
InitialContext ctx=new InitialContext ();
Object o = ctx.lookup ("Java:comp/env/hibernate");
Out.print ("class=" +o.getclass (). GetName ());
DataSource ds= (DataSource) o;
.......
That is, using the reflection API to print out the class full name of the data source object registered in Jndi, you will know that the original data source is a "Org.apache.commons.dbcp.BasicDataSource" object, and this class is in the%tomcat%\ Common\lib under the Commons-dbcp-1.2.1.jar bag, and its associated with Commons-collections-3.1.jar, Commons-pool-1.2.jar.
Add the above three packages to the current working environment, and use the following code to invoke the connection pool. I use the MySQL database, please join MySQL JDBC driver and%tomcat%\common\lib under Naming-java.jar when debugging
public static void Main (string[] args) throws Hibernateexception {
try{
Basicdatasource BDDs = new Basicdatasource ();
Setting up a database driver
Bdds.setdriverclassname ("Org.gjt.mm.mysql.Driver");
Set the URL for JDBC
Bdds.seturl ("Jdbc:mysql://localhost/sample");
Bdds.setusername ("root");
Bdds.setpassword ("1234");
Set Connection Pool Initial size
Bdds.setinitialsize (2);
Jndi Configuration
Hashtable env = new Hashtable ();
Env.put ("Java.naming.factory.initial", "org.apache.naming.java.javaURLContextFactory");
InitialContext ctx=new InitialContext (env);
Data source binding to Jndi
Ctx.bind ("Tomcatds", BDDs);
Find a data source in Jndi
DataSource ds = (DataSource) ctx.lookup ("Tomcatds");
Connection con = ds.getconnection ();
Statement stmt = Con.createstatement ();
String strSQL = "SELECT * from user";
ResultSet rs = stmt.executequery (strSQL);
while (Rs.next ()) {
System.out.println ("id=" +rs.getstring (1));
}
Rs.close ();
Stmt.close ();
Con.close ();
}catch (Exception ex) {
System.out.print (Ex.tostring ());
}
}