tomcat7.0.42如何设置mysql数据库连接池

diy112 发布于 2013/11/18 21:12
阅读 2K+
收藏 2

如何在tomcat7.0.42中设置mysql数据库连接池????eclipse如何绑定tomcat??按网上教程总不成功!怎么办??

加载中
0
南湖船老大
南湖船老大

server.xml

<Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource" factory="org.apache.tomcat.jdbc.pool.DataSourceFactory" testWhileIdle="true" testOnBorrow="true" testOnReturn="false" validationInterval="30000" timeBetweenEvictionRunsMillis="30000" maxActive="100" minIdle="10" maxWait="10000" initialSize="10" removeAbandonedTimeout="60" removeAbandoned="true" logAbandoned="false" minEvictableIdleTimeMillis="30000" jmxEnabled="true" jdbcInterceptors="org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer"  username="root" password="123" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/test"/>

<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
<Context docBase="blog3" path="/blog3" reloadable="true" source="org.eclipse.jst.jee.server:blog3"/>
</Host>

context.xml

<ResourceLink global="jdbc/test" name="jdbc/test" type="javax.sql.DataSource" />
Java代码:

public class DBconn {
	private static String datasoucename = "java:comp/env/jdbc/test";
	Context context = null;
	DataSource ds = null;
	Connection conn = null;

	public Connection getconn() {
		return initConnection();
	}

	public DataSource getDataSource() {
		try {
			context = new InitialContext();
		} catch (NamingException e) {
			System.err.println("连接池上下文不存在! " + e.getMessage());
		}
		try {
			ds = (DataSource) context.lookup(datasoucename);
		} catch (NamingException e) {
			System.err.println("数据源没发现! " + e.getMessage());
		}
		return ds;
	}

	private Connection initConnection() {
		try {
			context = new InitialContext();
		} catch (NamingException e) {
			System.err.println("连接池上下文不存在! " + e.getMessage());
		}
		try {
			ds = (DataSource) context.lookup(datasoucename);
		} catch (NamingException e) {
			System.err.println("数据源没发现! " + e.getMessage());
		}
		try {
			conn = ds.getConnection();
		} catch (SQLException e) {
			System.err.println("获取连接失败! " + e.getMessage());
		}
		return conn;
	}

	public void freeConnection() {
		try {
			conn.close();
		} catch (Exception e) {
			System.err.println("释放连接出错! ");
			e.printStackTrace();
		}
	}

}

返回顶部
顶部