目的:
實現多數據源的配置訪問。
配置文件示例:
<id="querycodedict" ds="sysds"> select * from code_dict</id>
本文並沒有使用此配置文件進行模擬,但整個過程完全相似,如果以此配置文件爲準,需要編寫對此文件的解析過程
服務器:
tomcat5.5
數據庫:
mysql5.0
準備:
建立兩個數據庫
數據庫1:javatest
mysql> GRANT ALL PRIVILEGES ON *.* TO javauser@localhost IDENTIFIED BY 'javadude' WITH GRANT OPTION; mysql> create database javatest; mysql> use javatest; mysql> create table testdata ( -> id int not null auto_increment primary key, -> foo varchar(25), -> bar int);
mysql> insert into testdata values(null, 'hello', 12345); Query OK, 1 row affected (0.00 sec) mysql> select * from testdata; +----+-------+-------+ | ID | FOO | BAR | +----+-------+-------+ | 1 | hello | 12345 | +----+-------+-------+ 1 row in set (0.00 sec) mysql>
數據庫2:systest
mysql> GRANT ALL PRIVILEGES ON *.* TO sysuser@localhost IDENTIFIED BY 'javadude' WITH GRANT OPTION;
Query OK, 0 rows affected (0.06 sec)
mysql> create database systest;
Query OK, 1 row affected (0.02 sec)
mysql> use systest;
Database changed
mysql> create table code_dict(
-> id int not null auto_increment primary key,
-> foo varchar(25),
-> bar int);
Query OK, 0 rows affected (0.14 sec)
mysql> insert into code_dict values(null, 'hello', 12345);
Query OK, 1 row affected (0.05 sec)
mysql> select * from code_dict;
+----+-------+-------+
| id | foo | bar |
+----+-------+-------+
| 1 | hello | 12345 |
+----+-------+-------+
1 row in set (0.00 sec)
mysql>
編寫配置文件:
tomcat家目錄下有conf文件夾,其中有一個context.xml文件
配置如下:
添加jbdc驅動:
tomcat家目錄下有common文件夾,將mysq驅動放入其中的lib下
編寫代碼測試:
建立一個web工程,編寫一個servlet進行測試
web.xml文件配置如下:
編寫java代碼,JNDIBinding類中的代碼在servlet中doGet方法中調用
在地址欄中輸入以下內容
http://localhost:8081/DBTest/servlet/JNDIServlet?name=123
運行後中控制檯中可以看到查詢結果
另特別說明:
此過程中遇到過找不到驅動問題,最後看官方文檔發現驅動應該放在common目錄下的lib下,如在網上找貼學習,此錯誤容易遇到