Tomcat中配置数据源连接池
一、 找到Tomcat所在目录中的的conf文件夹中的context.xml文件 在其中做修改
修改如下:
<Context> <WatchedResource>WEB-INF/web.xml</WatchedResource> <!—mysql数据源配置--> <Resource name="jdbc/mysqlds" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdel="30" maxWait="10000" username="root" password="5982285" driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost/myblog" /> <!—oracle数据源配置--> <Resource name="jdbc/oracleds" auth="Container" type="javax.sql.DataSource" maxActive="100" maxIdel="30" maxWait="10000" username="scott" password="tiger" driverClassName="oracle.jdbc.driver.OracleDriver" url="jdbc:oracle:thin:@localhost:1521:sky" /> </Context> |
属性说明:name: 数据源名称,通常取jdbc/XXX的格式
auth: Container容器
type: javax.sql.DataSource 注意是javax不是java
username: 数据库用户名
password: 数据库用户密码
maxIdle: 最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连
接将被标记为不可用,然后被释放。设为0表示无限制。
maxActive: 连接池的最大数据库连接数。设为0表示无限制。
maxWait : 最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示
无限制。
driveClassName: 数据库完整的驱动类全称
url: 数据库的链接
网上很多人都说需要在web.xml文件中再配置 其实补配置也是可以的
配置了<WatchedResource>WEB-INF/web.xml</WatchedResource> 之后 就无需在web.xml文件中配置了
或者是在context.xml中配置的而不是server.xml配置 因此不需要在web.xml中配置 没有测试
二、获取数据源中的连接
public class BlogServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String title = request.getParameter("title"); String content = request.getParameter("content"); String categoryId = request.getParameter("category");
DataSource ds = null; try { Context context = new InitialContext(); ds = (DataSource)context.lookup("java:comp/env/jdbc/mysqlds"); Connection con = ds.getConnection(); String sql = "insert into blog(title,category_id,content,created_time) values(?,?,?,now())"; PreparedStatement ps = con.prepareStatement(sql); ps.setString(1, title); ps.setInt(2, Integer.parseInt(categoryId)); ps.setString(3, content); int result = ps.executeUpdate(); System.out.println(result); } catch (NamingException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } }
} |
//初始化查找命名空间
Context initContext = new InitialContext();
//找到DataSource
DataSource ds = (DataSource)initContext.lookup(“java:comp/env/jdbc/mysqlds”);
//通过DataSource获取连接对象
Connection conn = ds.getConnection();
//将连接对象放回到数据源中 此处是放回 ,不是关闭
Conn.close();
Context à通过Context找到 DataSource à 通过DataSource获取连接对象