DBCP是tomcat内置的连接池。
使用方法:
- 导入jar包
书写配置文件
- 配置文件名称:*.properties(文件名任意,但是扩展名固定)。
- 位置任意,一般放在src目录下。
- 不能写中文。
内容(其他配置也写在这里面):
driver=com.mysql.jdbc.Driver url=jdbc:mysql://127.0.0.1:3306/ning username=root password=root
工具类:
package com.sunxiaoning.jdbc.utils; import java.io.InputStream; import java.sql.Connection; import java.sql.SQLException; import java.util.Properties; import javax.sql.DataSource; import org.apache.commons.dbcp.BasicDataSourceFactory; /** * DBCP工具类 * @author sunxiaoning * */ public class DBCPUtils { private static DataSource dataSource; static { try { //1.加载找properties文件输入流 InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties"); //2.加载输入流 Properties props = new Properties(); props.load(is); //3.创建数据源 dataSource = BasicDataSourceFactory.createDataSource(props); } catch (Exception e) { throw new RuntimeException(); } } /** * 获取数据源(连接池) * @return */ public static DataSource getDataSource() { return dataSource; } /** * 获得连接 * @return */ public static Connection getConnection() { try { return dataSource.getConnection(); } catch (SQLException e) { throw new RuntimeException(); } } }
测试类
package com.sunxiaoning.jdbc.test; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import org.junit.jupiter.api.Test; import com.sunxiaoning.jdbc.utils.DBCPUtils; public class TestDBCP { @Test public void testUpdateByid() { Connection conn = null; PreparedStatement pstmt = null; try { conn = DBCPUtils.getConnection(); String sql = "update users set upwd =? where uid =?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, "222"); pstmt.setInt(2, 1); int rows = pstmt.executeUpdate(); if(rows>0) { System.out.println("更新成功"); }else { System.out.println("更新失败"); } } catch (Exception e) { throw new RuntimeException(); }finally { if (conn!=null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if(pstmt!=null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } } }