分类: Mysql/postgreSQL
2010-11-10 15:37:41
tomcat数据库连接池配置
主要三个关键:
1 配置%TOMCAT_HOME%/conf/server.xml
2 配置%TOMCAT_HOME%/webapps/yourapp/WEB-INF/web.xml
3 将MySQL的JDBC驱动mysql-connector-java-bin.jar放到Tomcat\common\lib下面
环境:
mysql 5。0
tomcat 5.5注意这个版本,自己在tomcat 5.5 中总是出现错误:
Cannot create JDBC driver of class '' for connect URL 'null'
后来发现是在 server.xml 中配置时格式必须采用(tomcat5.5)
crossContext="true">
type="javax.sql.DataSource" maxActive="100"
maxIdle="30" maxWait="1000"
username="root" password=""
driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/dstest?autoReconnect=true"/>
而不能是下文的形式!
如用下文形式,则不能使用数据源方式连接数据库。应采用传统的:
//加载Connector/J驱动
//这一句也可写为:Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.mysql.jdbc.Driver").newInstance();
//建立到MySQL的连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dstest",
"root", "");
//执行SQL语句
首先,建一个数据库,dstest
建表test
-- 表的结构 `test`
CREATE TABLE `test` (
`id` int(11) NOT NULL auto_increment,
`name` varchar(30) NOT NULL default '',
`address` varchar(50) default NULL,
PRIMARY KEY (`id`)
) TYPE=MyISAM AUTO_INCREMENT=20 ;
-- 表中的数据 `test`
INSERT INTO `test` (`id`, `name`, `address`) VALUES (1, 'tom', '123');
INSERT INTO `test` (`id`, `name`, `address`) VALUES (2, 'tom', '123');
INSERT INTO `test` (`id`, `name`, `address`) VALUES (3, 'tom', '123');
将MySQL的JDBC驱动mysql-connector-java-bin.jar放到Tomcat\common\lib下面
配置tomcat数据源
编辑tomcat\conf\server.xml
在
切记要加在
郁闷了一个晚上(:
后来在tomcat\webapps\tomcat-docs下面发现了jndi-resources-howto.html,上面说
To
configure Tomcat's resource factory, add an elements like this to the
$CATALINA_HOME/conf/server.xml file, nested inside the Context element
for this web application (or nested inside a DefaultContext element for
the surrounding
在tomcat\webapps建一个目录dstest(同server.xml的中
dstest\WEB-INF
dstest\WEB-INF\classes
在dstest\WEB-INF下建web.xml
内容如下:
xsi:schemaLocation="
version="2.4">
30
datasource jdbc/testpool
jdbc/testpool
javax.sql.DataSource
Container
index.jsp
index.html
index.htm
测试
dstest.jsp
<%@ page language="java"%>
<%@ page import="java.util.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="javax.sql.*" %>
<%@ page import="javax.naming.*" %>
<%
String jndi_name="java:comp/env/jdbc/testpool";
String select_user_sql="select * from test";
Context ctx = new InitialContext();
if(ctx == null )
throw new Exception("No Context");
DataSource ds = (DataSource)ctx.lookup(jndi_name);
Connection conn = ds.getConnection();
try {
PreparedStatement psPreparedStatement=conn.prepareStatement(select_user_sql);
ResultSet resultSet = psPreparedStatement.executeQuery();
while(resultSet.next()){
out.print(""); ");
out.print(""+resultSet.getInt(1)+" ");
out.print(""+resultSet.getString(2)+" ");
out.print(""+resultSet.getString(3)+" ");
//out.print("KK ");
out.print("
}
}
catch(SQLException e){
e.printStackTrace();
}
finally {
conn.close();
}
%>
结果output:
Test Database Source Pools
1 |
tom |
123 |
2 |
tom |
123 |
3 |
tom |
123 |