tomcat MySQL数据源的实际操作流程与代码


  本文标签:tomcat MySQL

  以下的文章主要向大家描述的是tomcat MySQL数据源的实际操作流程以及在其实际操作中所要用到的代码的描述,假如你对实现tomcat MySQL数据源的实际操作感兴趣的话,以下的文章将会满足你这一兴趣  。

  1.拷相应的driver.jar到Tomcat5\common\lib下

  2.更改Tomcat5\conf下的context.xml

  节点下加

  1. <Resource name="jdbc/MysqlConnectionPoolTest" auth="Czh" 
  2. type="javax.sql.DataSource" driverClassName="com.mysql.jdbc.Driver" 
  3. url="jdbc:mysql://127.0.0.1:3306/test" 
  4. username="root" password="000000" maxActive="20" maxIdle="10" 
  5. maxWait="-1"/>  

  3.更改工程下的web.xml

  节点下加

  1. <resource-ref> 
  2. <description>DB Connectiondescription> 
  3. <res-ref-name>jdbc/MysqlConnectionPoolTestres-ref-name> 
  4. <res-type>javax.sql.DataSourceres-type> 
  5. <res-auth>Czhres-auth> 
  6. resource-ref> 

  4.tomcat MySQL数据源代码如下

  1. Context context = null;  
  2. Connection conn = null;  
  3. Statement stmt = null;  
  4. ResultSet rs = null;  
  5. public void DoQuery(String sql) {  
  6. try {  
  7. if(context==null)  
  8. {  
  9. context = new InitialContext();  
  10. }  
  11. // get ds  
  12. DataSource ds = (DataSource) context  
  13. .lookup("java:comp/env/jdbc/MysqlConnectionPoolTest");  
  14. // get conn  
  15. if(conn==null){  
  16. conn = ds.getConnection();  
  17. }  
  18. if(stmt==null){  
  19. stmt = conn.createStatement();  
  20. }  
  21. rs = stmt.executeQuery(sql);  
  22. while (rs.next()) {  
  23. String a = rs.getString("a");  
  24. String b = rs.getString("b");  
  25. }  
  26. } catch (Exception e) {  
  27. e.printStackTrace();  
  28. }  
  29. }  

  注意有comp/env/

  1. context  
  2. .lookup("java:comp/env/jdbc/MysqlConnectionPoolTest");  

  以上的相关内容就是对tomcat MySQL数据源的介绍,望你能有所收获  。