Tomcat Mysql datasource 資料來源配置

來源:互聯網
上載者:User
好像Tomcat6的資料來源配置比較簡單一些,不過如果按照以前版本的方法設定的話,會出現很多問題如:
Name jdbc is not bound in this Context
或者 Cannot create JDBC driver of class '' for connect URL 'null'等等
我把我用Tomcat6和Mysql5.17配置資料來源的步驟寫出來,大家可以參考一下
1. 下載mysql-connector-java-5.1.7-bin.jar,放到Tomcat安裝目錄下的lib檔案夾下;
2. 在你的項目下的META-INF檔案夾下(如果沒有就建立一個,跟WEB-INF檔案夾同級)建立一個context.xml檔案;
    內容如下
  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <Context>
  3.   <Resource name="jdbc/datasource_name" auth="Container"
  4.             type="javax.sql.DataSource" username="root" password="xxxxxxx"
  5.             driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/database_name"
  6.             maxActive="8" maxIdle="4"
  7.             testOnBorrow="true"
  8.             validationQuery="select 1"
  9.             timeBetweenEvictionRunsMillis="30000"
  10.             />
  11. </Context>

3.  替換以上的datasource_name為你的資料來源名字, database_name為你的資料庫名字, password也改成你的
4.  在你的Java代碼裡驗證是否成功
     

  1. InitialContext initContext = new InitialContext();
  2. DataSource ds = (DataSource)initContext.lookup("java:comp/env/jdbc/datasource_name"); 
  3. Connection conn = ds.getConnection();
  4.         
  5. Statement ps = conn.createStatement();
  6. ResultSet rs = ps.executeQuery("select * from table_name");
  7. while(rs.next())
  8. {
  9.     System.out.println(rs.getString(2));
  10. }  

5.應該可以看到輸出的資訊了

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.