龙盟编程博客 | 无障碍搜索 | 云盘搜索神器
快速搜索
主页 > 数据库类 > MySQL 技术 >

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

时间:2011-04-12 23:18来源:未知 作者:admin 点击:
分享到:
以下的文章主要向大家描述的是tomcat M ySQL 数据源的实际操作流程以及在其实际操作中所要用到的代码的描述,假如你对实现tomcat MySQL数据源的实际操作感兴趣的话,以下的文章将会满

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

1.拷相应的driver.jar到Tomcat5commonlib下

2.更改Tomcat5conf下的context.xml

<Context>节点下加

  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

<web-app>节点下加

  1. <resource-ref> 
  2. <description>DB Connection</description> 
  3. <res-ref-name>jdbc/MysqlConnectionPoolTest</res-ref-name> 
  4. <res-type>javax.sql.DataSource</res-type> 
  5. <res-auth>Czh</res-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数据源的介绍,望你能有所收获。


精彩图集

赞助商链接