• 连接池


    一,JDBC的删改查操作
      删,改同添加一样
      ★,查询
        ResultSet rs=state.executeQuery("Select * From products;");
        while(rs.next()){
          Int pid=rs.getInt(“pid”);
          String pname=rs.getString(“pname”);
        }
     
    二,PreparedStatement
      1,SQL注入攻击
        指用户根据编写程序的漏洞,使用SQL语句对数据库进行攻击,获取数据库信息
      2,解决SQL注入攻击
        方法:
          使用Statement接口的子接口--》java.sql.PreparedStatement extends Statement
        步骤:
          1,获取PreparedStatement对象
            PreparedStatement pst=conn.prepareStatement(String sql);
            sql语句可以使用占位符 ?
          2,设置占位符 ?的数据
            pst.setObject(1,username);
          3,执行SQL语句
            返回 int       pst.executeUpdate();   用于 insert update delete
            返回 ResultSet     pst.executeQuery();   用于 select
     
    三,用连接池重写工具类
      原理:
        连接池--》一个容器--》java中的集合--》养一些链接 Connection  集合常用LinkedList ArrayList,HashSet,HashMap
      规范:
        连接池是不同厂家生产的连接数据库的一种工具,DBCP C3P0 德鲁伊
        java中出面定制了一套连接池的规范,javax.sql.DataSource 接口,定义了从连接池中获取连接的抽象方法,getConnection();
        对于使用者,我们只需要知道getConnection方法是从连接池中获取连接,而无需关注每种连接池的内部实现 ----》这就是面向接口的编程
      使用:
        0,导入jar包
        1,在成员位置,创建一个静态的ComboPooledDataSource对象
        2,在静态代码块中使用 CPDS对象.setXXX方法 设置数据库连接
        3,定义一个静态方法, CPDS对象中获取数据库连接Connection
        4,释放资源
     
    public class PSUtils {
    //0 导入查jar包
    // * 1 在成员变量位置 创建一个静态ComboPooledDataSource对象
    private static ComboPooledDataSource ds=new ComboPooledDataSource();
    // * 2 在静态d代码块使用ComboPooledDataSource对象 setxxxx 方法 设置数据库连接
    static {
    try {
    ds.setDriverClass("com.mysql.jdbc.Driver");
    ds.setJdbcUrl("jdbc:mysql://127.0.0.1:3306/day05");
    ds.setUser("root");
    ds.setPassword("root");
    } catch (PropertyVetoException e) {
    e.printStackTrace();
    }
    }
    // * 3 定义一个静态方法ComboPooledDataSource对象中获得数据库连接Connection
    public static Connection get(){
    try {
    return ds.getConnection();
    } catch (SQLException e) {
    throw new RuntimeException("连接失败!");
    }
    }
    // * 4 释放资源
    public static void close(ResultSet rs, Statement state,Connection conn){
    if (rs!=null){
    try {
    rs.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    if (state!=null){
    try {
    state.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    if (conn!=null){
    try {
    conn.close();
    } catch (SQLException e) {
    e.printStackTrace();
    }
    }
    }
    }
  • 相关阅读:
    Oracle block 格式
    oracle用户解锁
    如何扩大重做日志(redolog)文件的大小
    Oracle重建临时表空间
    ORA-32004: obsolete and/or deprecated parameter(s) specified
    oracle分布式事务总结(转载)
    spring注解 @Scheduled(cron = "0 0 1 * * *")实现定时的执行任务
    IDEA启动Tomcat报错1099 is already in use
    js中const,var,let区别
    mysql笔记
  • 原文地址:https://www.cnblogs.com/kide1412/p/11010031.html
Copyright © 2020-2023  润新知