现在的位置: 首页 > 综合 > 正文

jsp中如何使用数据库连接池

2018年01月10日 ⁄ 综合 ⁄ 共 1274字 ⁄ 字号 评论关闭

 

jsp_数据库连接池
步骤:
1.。在你所在的项目的webroot下的META-INF下新建一个contex.xml的文件。
里面写上如下内容:(本人用的JDBC 2.0)
<?xml version="1.0" encoding="UTF-8"?>
<Context reloadable="true" crossContext="true"> 
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<Resource  
name="jdbc/a"  
auth="Container"  
type="javax.sql.DataSource"  
driverClassName="com.microsoft.jdbc.sqlserver.SQLServerDriver"  
url="jdbc:microsoft:sqlserver://localhost:1433;databaseName=webdb"  
maxActive="200"  
maxldle="60"  
maxWait="10000"  
username="sa"  
password="139547"  
/>  
</Context> 

2.。然后在你的web.xml文件中(最前面!!)写上如下内容
<resource-ref>
 <description>db connection </description>
 <res-ref-name>jdbc/a</res-ref-name>
 <res-type>javax.sql.DataSource</res-type>
 <res-auth>Container</res-auth>
</resource-ref>

3 。在你java程序连接数据库的类中添加如下代码:
package com.lxr;
import java.sql.*;

import javax.naming.*;
import javax.sql.DataSource;

public class ConnDB {
 private Connection ct=null;

 public static Connection getConn(){
 try {
  
  Context ctx=new InitialContext();
  Context envContext=(Context)ctx.lookup("java:comp/env");
  DataSource ds=(DataSource)envContext.lookup("jdbc/a");
  ct=ds.getConnection();
  System.out.println("连接池连接成功");
  
 } catch (Exception e) {
  System.out.prinln("数据库连接失败!");
  e.printStackTrace();
 }
 

 return ct;
}
}
4         如果再别的类中调用,即写上;
Connection ct=ConnDB.getConn();
这样就数据库连接池就ok了

 

抱歉!评论已关闭.