好像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檔案;
內容如下
- <?xml version="1.0" encoding="UTF-8"?>
- <Context>
- <Resource name="jdbc/datasource_name" auth="Container"
- type="javax.sql.DataSource" username="root" password="xxxxxxx"
- driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/database_name"
- maxActive="8" maxIdle="4"
- testOnBorrow="true"
- validationQuery="select 1"
- timeBetweenEvictionRunsMillis="30000"
- />
- </Context>
3. 替換以上的datasource_name為你的資料來源名字, database_name為你的資料庫名字, password也改成你的
4. 在你的Java代碼裡驗證是否成功
- InitialContext initContext = new InitialContext();
- DataSource ds = (DataSource)initContext.lookup("java:comp/env/jdbc/datasource_name");
- Connection conn = ds.getConnection();
-
- Statement ps = conn.createStatement();
- ResultSet rs = ps.executeQuery("select * from table_name");
- while(rs.next())
- {
- System.out.println(rs.getString(2));
- }
5.應該可以看到輸出的資訊了