zoukankan      html  css  js  c++  java
  • JDBC和连接池

    JDBC
    所有的数据库操作框架都是用在JDBC的基础上做多次封装的,因为JDBC的操作很复杂

    • 引入Jar包
    • 连接数据库操作
    • 书写sql语句,传参
    • 查询,取值
    • 关闭连接
    //1.注册驱动(静态方法)(包名+类名)
    Class.forName("com.mysql.jdbc.Driver");
    //2.获取连接对象(导包都导sql里面的,不导jdbc里的;多态!报异常是因为用户输入的串可能写错)后面设置下数据格式
    String url="jdbc:mysql://localhost:3306/java0603?useUnicode=true&characterEncoding=UTF-8";
    String user="root";
    String password="123456";
    // 3.连接数据库
    Connection conn=DriverManager.getConnection(url,user,password);
    // 写sql语句
    String sql="select count(*) from user where uname=? and pwd=?";
    PreparedStatement pst=conn.prepareStatement(sql);
    //给sql语句的?赋值
    pst.setString(1,"pdt1997");
    pst.setString(2, "xxxx");
    ResultSet rs= pst.executeQuery();
    
    //5.处理结果集
    int count=0;
    while(rs.next()){
        count=rs.getInt(1);//因为就一列
        System.out.println(count);
    }
    //6.释放资源
    rs.close();
    pst.close();
    conn.close();
    

    因为每次操作都需要连接一次,结束需要断开一次,所有就需要封装一个永远在连接状态的单例模式工具库

    public class JDBCUtils {
        //获取连接对象的方法(静态的)
        public static  Connection getConn(){
            Connection conn=null;
            try {
               //1.注册驱动(静态方法)(包名+类名)
               Class.forName("com.mysql.jdbc.Driver");
               //2.获取连接对象(导包都导sql里面的,不导jdbc里的;多态!报异常是因为用户输入的串可能写错)后面设置下数据格式
               String url="jdbc:mysql://localhost:3306/java0603?useUnicode=true&characterEncoding=UTF-8";
               String user="root";
               String password="123456";
               conn=DriverManager.getConnection(url,user,password);
           } catch (ClassNotFoundException | SQLException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();
           }
           return conn;    
        }
        //释放资源
        public static void close(Connection conn,Statement sta){
            if(sta!=null){
                try {
                    sta.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
        //释放资源2
        public static void close(Connection conn,Statement sta,ResultSet rs){
            if(rs!=null){
                try {
                    rs.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(sta!=null){
                try {
                    sta.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if(conn!=null){
                try {
                    conn.close();
                } catch (SQLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    
    public static void main(String[] args) {
        //1.获得连接对象
        Connection conn=JDBCUtils.getConn();
        //测试下是地址不System.out.println(conn);
        //2.获取语句执行平台
        String sql="insert into test (name) values(?)";
        PreparedStatement pst=conn.prepareStatement(sql);
        //3.执行sql
        pst.setString(1, "xxx");
        int row=pst.executeUpdate();
        System.out.println(row);
        //4.释放资源
        JDBCUtils.close(conn, pst);
    }
    

    连接池
    现在常用的开源数据连接池主要有c3p0dbcp两种

    • dbcp没有自动的去回收空闲连接的功能,c3p0有自动回收空闲连接功能
    • 两者主要是对数据连接的处理方式不同!C3P0提供最大空闲时间,DBCP提供最大连接数,C3P0当连接超过最大空闲连接时间时,当前连接就会被断掉;DBCP当连接数超过最大连接数时,所有连接都会被断开
    public class DBCPUtil {
    
        private static DataSource dataSource;
    
        static{
            try{
                //1、将properties文件夹在到输入流中
                InputStream is = DBCPUtil.class.getClassLoader().getResourceAsStream("dbcp.properties");
                //2、创建properties对象,用于读取第一步得到的输入流
                Properties ps = new Properties();
                //3、使用上述的properties对象,加载本地的properties文件
                ps.load(is);
                //4、使用连接池工厂类,创建连接池对象
                DataSource dataSource = BasicDataSourceFactory.createDataSource(ps);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    
        //用于从连接池中,获取一个连接对象的操作方法
        public static Connection getConnection(){
            try{
                return dataSource.getConnection();
            }catch (Exception e){
                e.printStackTrace();
                return null;
            }
        }
    
        //用于释放数据库的连接资源
        public static void close(Connection conn, Statement state,ResultSet resultSet){
            try{
                if(conn!=null){
                    conn.close();
                    conn = null;
                }
                if(state!=null){
                    state.close();
                    state = null;
                }
                if (resultSet!=null){
                    resultSet.close();
                    resultSet = null;
                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }
    
    public static void main(String[] args) {
        Connection connection = null;
        PreparedStatement ps = null;
        try {
            connection = DBCPUtil.getConnection();
            String sql = "insert into users(username,password) values(?,?)";
            ps = connection.prepareStatement(sql);
            ps.setString(1, "张三");
            ps.setString(2, "123456");
            ps.execute();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            DBCPUtils.close(connection, ps);
        }
    }
    

    配置文件

    # 连接设置
    driverClassName=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/jdbc
    username=root
    password=
    
    # 初始化连接
    initialSize=10
    # 最大连接数量
    maxActive=200
    # 最大空闲连接
    maxIdle=20
    # 最小空闲连接
    minIdle=5
    
    # 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒
    maxWait=60000
    
    # JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;] 
    # 注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们
    connectionProperties=useUnicode=true;characterEncoding=UTF8
    
    # 指定由连接池所创建的连接的自动提交(auto-commit)状态。
    defaultAutoCommit=true
    

    了解一下就好,这个不是开发用的,开发现在还是用mybatis

  • 相关阅读:
    什么是HTTP
    通过递归法解决阶梯问题(n个台阶,上楼可以一步上1阶,也可以一步上2阶,一共有多少种上楼的方法)
    在Intelli Idea中使用plantuml(plantuml时序图的使用)
    Java中if(boolean)与if(boolean=true)的区别
    实现一个Servlet程序
    退出mysql的编辑模式
    mysql数据库基本操作命令行
    通过mysql命令查看mysql服务实例支持的搜索引擎
    Mac环境下使用终端启动Mysql,并进行mysql数据库的连接
    路飞学城Python-Day4
  • 原文地址:https://www.cnblogs.com/pengdt/p/12240540.html
Copyright © 2011-2022 走看看