数据库连接池连接方法:

先要下载好数据库连接驱动jar文件:mysql-connector-java-5.1.22-bin 放在tomcat的lib文件夹下,并在然后根据以下两种方法加以配置:

1、全局方法:
在tomcat的conf目录下打开context.xml加入代码:ConnectionPool为连接池名字,可随便取,但是要对应;newsmanagersystem为数据库名
<Context>
<Resource
name = "jdbc/myconn"
auth = "Container"
type = "javax.sql.DataSource"
password = "root"
driverClassName = "com.mysql.jdbc.Driver"
maxIdle = "10"
maxWait = "1000"
username = "root"
url = "jdbc:MYSQL://localhost:3306/study?characterEncoding=GBK"
maxActive = "8"/>

<WatchedResource>Web-INF/web.xml</WatchedResource>
</Context>

然后在工程的web.xml文件中加入代码:
<resource-ref>
<description>GuestBook</description>
<res-ref-name>jdbc/myconn</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>

 

2、对某一个Web项目的方法:
在META-INF文件夹下context.xml文件中加入代码:
<Context>
<Resource
name = "jdbc/myconn"
auth = "Container"
type = "javax.sql.DataSource"
password = "root"
driverClassName = "com.mysql.jdbc.Driver"
maxIdle = "10"
maxWait = "1000"
username = "root"
url = "jdbc:MYSQL://localhost:3306/newsmanagersystem?characterEncoding=GBK"
maxActive = "8"/>

<WatchedResource>Web-INF/web.xml</WatchedResource>
</Context>


根据以上两种方法就可在程序中创建数据源对象:
Context ctx = new InitialContext();
Context ctxing = (Context) ctx.lookup("java:comp/env");
//获取连接池对象
DataSource ds =(DataSource)ctxing.lookup("jdbc/ConnectionPool");
//创建连接
Connection conn = ds.getConnection();
Statement st= conn.createStatement();

posted @ 2018-01-11 22:07  carrie0608  阅读(218)  评论(0编辑  收藏  举报