美文网首页
jdbc与连接池使用

jdbc与连接池使用

作者: 61etj | 来源:发表于2018-10-28 00:08 被阅读0次

JDBC使用

  • 导包

将mysql-connector-java.jar导入项目

  • 注册驱动

      Class.forName("com.mysql.jdbc.Driver");//推荐
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());//不推荐,此方法会注册两次,硬编码不利于维护
    
  • 获取链接

      Connection conn=DriverManager.getConnection("jdbc:mysql:localhost:3306/web08","root","root");
      //参数一为
      //jdbc:  mysql:    localhost:  3306  /  web08     ?   useUnicode=true   characherEncoding=UTF8
      //协议  数据库类型      地址      端口     数据库名称     使用Unicode字符集        使用UTF8编码
      //参数二为登录账号
      //参数三位登录密码
      //返回值为连接对象
    
  • 创建执行sql语句的对象

    Statement会有注入漏洞,不推荐使用

      Statement stmt=conn.createStatement();
    

    预处理对象PreparedStatement,解决了注入漏洞,提高可读性,维护性, 效率

      PreparedStatement psmt=conn.prepareStatement(sql);
    
  • 执行sql语句

1. 使用Statement

    
    > 这里的sql语句中参数必须拼接好
    
        

2. 使用PreparedStatement

    > 这里的sql语句参数用 ? 当占位符,再用以下方法设置

        //设置参数
        psmt.setString(int index,String value);//参数一为位置从1开始,参数二为值
  • 获取结果中的数据

      ResultSet executeQuery("sql语句");//执行select(DQL)
      int executeUpdate("sql语句");//执行insert update delete(DML),返回影响行数
      
      boolean execute(String sql);//执行DML返回true,执行其他返回false
          如果返回true使用getResultSet()返回结果集
          如果返回false使用getUpdateCount()获得影响行数
    
      //批处理
      addBatch(String sql);
      clearBatch();
      executeBatch();
    
      //ResultSet有以下方法
      boolean next();//有数据会返回true
      Object getObject(int col);//获得任意对象
      String getString(int col);//获得字符串
      int getInt(int col);//获得整形
      double getDouble(int col);//获得双精度浮点型
    
  • 释放资源

    先得到的后关闭

      rs.close();
      stmt.close();
      con.close();
    
  • 事务

      Connection#setAutoCommit(boolean isAutoCommit);//关闭事务自动提交
      
      Connection#commit();//提交事务
    
      Connection#rollback();//回滚事务, 一般放在异常内
    

连接池

自定义连接池

  • 继承 javax.sql.DataSource

  • 创建连接池

      LinkedList<Connection> pool =new LinkedList<>();
    

    这里使用LinkedList因为连接池增删多,查询少

  • 初始化链接池

      static {
          for(...){
              pool.add(conn)//这里会循环获取Connection并且放入链接池中
          }
      }
    
  • 获取连接对象

      @Override
      Connection getConnection(){
          if(pool.size()==0){
              //给连接池增加Connection
          }
          
          //返回连接池内的Connection
          return pool.remove(0);
      }
    
  • 归还连接对象

      void backConnection(Connection conn){
          pool.add(conn);
      }
    

C3P0连接池

需要一个配置文件(xml,properties),然后一行代码即可获取连接池对象

  • 导包 c3p0-0.9.1.2.jar

  • 创建c3p0-config.xml配置文件,位于src下或者classpath下

      <?xml version="1.0" encoding="UTF-8"?>
      <c3p0-config>
      
        <default-config>
          <property name="driverClass">com.mysql.jdbc.Driver</property>
          <property name="jdbcUrl">jdbc:mysql:///web_07</property>
          <property name="user">root</property>
          <property name="password">123</property>
          <property name="initialPoolSize">5</property>
          <property name="maxPoolSize">20</property>
        </default-config>
        
        <named-config name="test"> 
          <property name="driverClass">com.mysql.jdbc.Driver</property>
          <property name="jdbcUrl">jdbc:mysql:///web_07</property>
          <property name="user">root</property>
          <property name="password">123</property>
        </named-config>
        
      
      </c3p0-config>
    
  • 使用

      ComboPooledDataSource dataSource = new ComboPooledDataSource(String name);//参数不填写会使用配置文件中的default-config,填写则会寻找配置文件中对应的
    

DBCP连接池

需要一个配置文件(properties),并且自己创造工具类,将properties文件读取并放入BaseicDataSourceFactory#createDataSource中创建连接池,提供连接池对象方法以及连接对象方法

  • 导包commons-dbcp-1.4.jar 以及 commons-pool-1.5.6.jar

  • 创建db.properties

      driver=com.mysql.jdbc.Driver
      url=jdbc:mysql://localhost:3306/web08?useUnicode=true&characterEncoding=utf8
      username=root
      password=root
    
  • 写一个DBCPUtils工具类加载db.properties文件

      static DataSource dataSource;
      static{
          InputStream is = DBCPUtils.class.getClassLoader().getResourceAsStream("db.properties");
          Properties props = new Properties();
          props.load(is);
          dataSource = BaseicDataSourceFactory.createDataSource(props);//核心,DBCP仅提供能接受 Properties 对象的构造
      }
    
      DataSource getDataSource(){return dataSource;}
      
      Connection getConnection(){
          return dataSource.getConnection();
      }

相关文章

网友评论

      本文标题:jdbc与连接池使用

      本文链接:https://www.haomeiwen.com/subject/mnfytqtx.html