一.JDBC增删改查
-
查询所有并展示
-
根据ID查询某条数据
- 添加一条数据
-
根据ID修改一条数据
-
根据ID删除一条数据
二.连接池
1.为什么要讲解连接池:
工作中为了提升和数据库的交互效率,处处都会使用连接池。
什么是连接池:用来保存和管理 Connection对象的容器
作用:保存、管理Connection对象
提升和数据库交互效率
降低服务器内存开销
2.原理
①如果连接池有空闲连接,取出空闲连接使用
②如果连接池没有空闲连接了,连接池会再创建一系列的空闲连接,供你取出使用
③如果连接池存在大量空闲连接长期未使用,连接池会销毁这些空闲连接
3,种类
- Mybatis中使用的druid连接池。
- 所有实现了javax.sql.DataSource接口的都是连接池类
4.框架中的连接池
druid连接池。
5,自定义连接池(扩展)
MyDataSource:
public class MyDataSource implements DataSource { private static final String DRIVERCLASS="com.mysql.jdbc.Driver"; private static final String URL="jdbc:mysql://127.0.0.1:3306/day01_db"; private static final String USERNAME="root"; private static final String PASSWORD="1234"; //连接池 private static final LinkedList<Connection> pool = new LinkedList<Connection>(); static{ //1、注册驱动 try { Class.forName(DRIVERCLASS); //2、初始化连接池,默认连接池有5个连接 initPool(); } catch (Exception e) { e.printStackTrace(); } } /** * 初始化连接池 */ private static void initPool() throws SQLException { for (int i = 0; i <5 ; i++) { pool.addLast(getCon()); } } /** * 类内部进行获取连接的方法 * @return */ private static Connection getCon() throws SQLException { return DriverManager.getConnection(URL,USERNAME,PASSWORD); } /** * 获取连接 * @return * @throws SQLException */ public Connection getConnection() throws SQLException { //判断:连接池是否有连接 if(pool.size()==0){ //连接池没有连接,再创建5个 initPool(); } //连接池有连接,从池中取出一个连接 return pool.removeLast(); } /** * 关闭所有资源 (con对象 归还到 连接池中) * @param con * @param ps * @param rs * @throws SQLException */ public static void closeAll(Connection con, PreparedStatement ps,ResultSet rs) throws SQLException { if(rs!=null) rs.close(); if(ps!=null) ps.close(); if(con!=null) pool.addLast(con); } public Connection getConnection(String username, String password) throws SQLException { return null; } public <T> T unwrap(Class<T> iface) throws SQLException { return null; } public boolean isWrapperFor(Class<?> iface) throws SQLException { return false; } public PrintWriter getLogWriter() throws SQLException { return null; } public void setLogWriter(PrintWriter out) throws SQLException { } public void setLoginTimeout(int seconds) throws SQLException { } public int getLoginTimeout() throws SQLException { return 0; } public Logger getParentLogger() throws SQLFeatureNotSupportedException { return null; } }
测试代码:
/* * 连接池演示 * */ public static void main(String[] args) throws Exception { //1、创建连接池 MyDataSource ds = new MyDataSource(); //2、通过连接池,获取连接 Connection con =ds.getConnection(); //3、获取发送SQL语句对象 PreparedStatement ps = con.prepareStatement("select * from category"); //4、发送SQL语句,返回结果集 ResultSet rs = ps.executeQuery(); while(rs.next()){ System.out.println("cid:"+rs.getInt("cid")+"t cname:"+rs.getString("cname")); } //5、关闭资源 ds.closeAll(con,ps,rs); }
看完恭喜你,又知道了一点点!!!
你知道的越多,不知道的越多!
~感谢志同道合的你阅读, 你的支持是我学习的最大动力 ! 加油 ,陌生人一起努力,共勉!!
注: 如果本篇有需要改进的地方或错误,欢迎大神们指定一二~~