概括一下, 大致分为四步: 安装驱动, 填充 context.xml, 填充 web.xml, 编写程序取得连接. 通过一个小 DEMO 对这种配置方式有了一点了解, 以 tomcat6.0 连接 mysql5.0.8 数据库为例.
安装驱动
下载与所要连接的数据库版本对应的 JDBC 驱动程序, 加入到应用的 CLASSPATH. 如果用 tomcat 部署, tomcat 中最好也加上(笔者觉得好像没必要加, 可是不加的话会报错...... 所以还是加了). 应该有办法不加的, 若有高手路过, 请指点.
填充 context.xml
这里就像是做声明样的, 把你要连接时的相关属性定义在里面. 我的配置如下:
- <Context crossContext="true" docBase="E:/workspace/myeclipse-workspace/WebDevDemo/WebRoot"
- path="/webdemo">
- <Resource name="jdbc/EmployeeDB" auth="Container" type="javax.sql.DataSource"
- username="root" password="" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/employee"
- maxActive="8" maxIdle="4" />
- </Context>
填充 Web.xml. 我的配置:
- <resource-ref>
- <res-ref-name>
- jdbc/EmployeeDB
- </res-ref-name>
- <res-type>
- javax.sql.DataSource
- </res-type>
- <res-auth>
- Container
- </res-auth>
- </resource-ref>
编写程序取得连接. 俺的程序:
- Context ctx = null;
- Context context = null;
- DataSource dataSource = null;
- Connection conn = null;
- PreparedStatement statement = null;
- ResultSet rs = null;
- try {
- ctx = new InitialContext();
- context = (Context) ctx.lookup("java:comp/env");
- dataSource = (DataSource)context.lookup("jdbc/EmployeeDB");
- } catch (NamingException e) {
- e.printStackTrace();
- }
- try {
- conn = dataSource.getConnection();// 获得连接
- // 取数据
- statement = conn.prepareStatement(SQL_FIND_ALL_SALARY_RECORDS);
- rs = statement.executeQuery();
- } catch (SQLException e) {
- e.printStackTrace();
- }
按照以上的方式就能在 tomcat 里以配置的形式连接数据库, 比我们把所有的连接属性都定义在类里要方便多了. 由于公司用的还是 5.0 版的 tomcat, 所以笔者也用这个进行了实验, 在操作上与 6.0 有两处不同:
(1)在上面的第一步, 加载驱动时. 若是 5.0 版的, 驱动的 JAR 包要放在 %CATALINA_HOME%\common\lib 下面; 若是 6.0 版的, 驱动的 JAR 包要放在 %CATALINA_HOME%\lib 下面.
(2)在上面的第二步, 声明连接的方式有所不同. 5.0 版比较复杂点, 需要像下面这样配:
- <Resource name="jdbc/EmployeeDB" auth="Container" type="javax.sql.DataSource"
- />
- <ResourceParams name="jdbc/EmployeeDB">
- <parameter>
- <name>
- username
- </name>
- <value>
- root
- </value>
- </parameter>
- <parameter>
- <name>
- password
- </name>
- <value>
- </value>
- </parameter>
- <parameter>
- <name>
- driverClassName
- </name>
- <value>
- com.MySQL.jdbc.Driver
- </value>
- </parameter>
- <parameter>
- <name>
- url
- </name>
- <value>
- jdbc:MySQL://localhost:3306/employee
- </value>
- </parameter>
- <parameter>
- <name>
- maxActive
- </name>
- <value>
- 8
- </value>
- </parameter>
- <parameter>
- <name>
- maxIdle
- </name>
- <value>
- 4
- </value>
- </parameter>
- </ResourceParams>
- </Context>
效果一样, 只是写法不同, 6.0 版本对配置文件做了简化, 所以看起来清爽一些. 呵呵, 这貌似就是软件的升级哦
来源: http://www.jianshu.com/p/a5c1cb2217ca