【数据库_05】JdbcTemplate

2021-02-04 10:48:22 浏览数 (1)

一、数据库连接池

1. 概述
代码语言:javascript复制
* 数据库连接池负责分配、管理和释放数据库连接,它允许应用程序重复使用一个现有的数据库连接,而不是再重新建立一个;
* 释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的数据库连接遗漏。【这项技术能明显提高对数据库操作的性能】
2. c3p0
代码语言:javascript复制
//配置文件
<c3p0-config>
  <!-- 使用默认的配置读取连接池对象 -->
  <default-config>
    <!--  连接参数 -->
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/db1</property>
    <property name="user">root</property>
    <property name="password">root</property>
    
    <!-- 连接池参数 -->
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">10</property>
    <property name="checkoutTimeout">3000</property>
  </default-config>
 
  <!-- 使用指定的配置读取连接池对象 -->
  <named-config name="otherc3p0">
    <!--  连接参数 -->
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/emp</property>
    <property name="user">work</property>
    <property name="password">work</property>
 
    <!-- 连接池参数 -->
    <property name="initialPoolSize">5</property>
    <property name="maxPoolSize">8</property>
    <property name="checkoutTimeout">1000</property>
  </named-config>
</c3p0-config>

//示例
import com.mchange.v2.c3p0.ComboPooledDataSource;
 
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
 
public class C3P0_Pool {
    public static void main(String[] args) {
 
        try {
            //创建数据库连接池,不需要指定文件名,自动查找src下 c3p0,properties / c3p0-config.xml
            DataSource ds = new ComboPooledDataSource();
            //获取连接
            Connection connection = ds.getConnection();
            //sql语句
            String sql = "select username from user where username = ? and password = password(?)";
            //获取执行sql对象
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            //给?赋值
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            //执行sql
            ResultSet resultSet = preparedStatement.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
}
3. druid
代码语言:javascript复制
//配置文件
<!-- 此项可以不配,通过url可以知道 -->
#driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/db1
username=work
password=gaohu
#initialSize=5
#maxActive=10
#maxWait=3000

//示例
import com.alibaba.druid.pool.DruidDataSourceFactory;
 
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;
 
public class Druid_Pool {
    public static void main(String[] args) {
        try {
            //创建properties集合
            Properties ps = new Properties();
            //获取druid.properties文件流
            InputStream is = Druid_Pool.class.getClassLoader()
                    .getResourceAsStream("druid.properties");
            //加载配置文件进内存
            ps.load(is);
            //获取数据库连接池
            DataSource dataSource = DruidDataSourceFactory.createDataSource(ps); //param : Map/Properties
            //获取连接对象
            Connection connection = dataSource.getConnection();
 
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
4. JDBCUtils(druid)
代码语言:javascript复制
import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
 
public class Utils {
    //提升作用域
    static DataSource dataSource = null;
 
    static {
        try {
            //创建properties集合
            Properties pro = new Properties();
            //加载配置文件进内存
            pro.load(Utils.class.getClassLoader().getResourceAsStream("druid.properties"));
            //创建数据库连接池
            dataSource = DruidDataSourceFactory.createDataSource(pro);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    /**
     *  获取数据库连接对象
     */
    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
 
    /**
     *  获取数据库连接池
     */
    public static DataSource getDataSource() {
        return dataSource;
    }
 
    /**
     *  释放资源
     */
    public static void close(ResultSet rs, Statement st, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
 
        //调用重载方法
        close(st,conn);
    }
 
    public static void close(Statement st, Connection conn) {
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
 
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

二、JDBCTemplate

1. 概述
代码语言:javascript复制
* Spring框架对JDBC的简单封装。提供了一个JDBCTemplate对象简化JDBC的开发
2. 构造方法
代码语言:javascript复制
public JdbcTemplate(DataSource);
    - JdbcTemplate template = new JdbcTemplate(ds);
3. 常用方法
代码语言:javascript复制
* execute()
    可以执行任何 sql,一般用来执行 DDL
* update()
    一般用来执行 DML,返回影响的行数
    【测试类】
        //数据库测试类一般使用回环 插入 -> 修改/查询 -> 删除
        import org.junit.Assert;
        import org.junit.FixMethodOrder;
        import org.junit.Test;
        import org.junit.runners.MethodSorters;
        import org.springframework.jdbc.core.JdbcTemplate;

        @FixMethodOrder(MethodSorters.NAME_ASCENDING)    //让测试方法按照名称顺序执行
        public class Druid_Test {
            //创建JDBCTemplate对象
            JdbcTemplate template = new JdbcTemplate(JDBCUtils.dataSource);
 
            @Test    //测试方法可以单独运行
            public void testA_Insert() {
                //sql语句
                String sql = "insert into user values(?,?,password(?))";
                //执行sql
                int i = template.update(sql, null, "rock", "rock");
                //判断
                Assert.assertEquals(1,i);
            }
 
            @Test
            public void testB_Update() {
                //sql语句
                String sql = "update user set password = password(?) where username = ?";
                //执行sql
                int i = template.update(sql, "123","rock");
                //判断
                Assert.assertEquals(1,i);
            }
 
            @Test
            public void testC_Delete() {
                //sql语句
                String sql = "delete from user where username = ?";
                //执行sql
                int i = template.update(sql, "rock");
                //判断
                Assert.assertEquals(1,i);
            }
        }
        
* queryMap()
    将一条记录n封装为 Map 集合,key 为字段,value 为值
* queryList()
    将每一条纪律封装为 Map 再将 Map 装到 List
* query(sql,BeanPropertyRowMapper<T>(T.class))
    将结果集封装为JavaBean
* queryForObject()                    
    将结果封装为对象(聚合函数)
-> queryForObject(sql,BeanPropertyRowMapper<T>(T.class))
    将一条记录封装为javabean
4. 示例
代码语言:javascript复制
//User
import java.util.Date;

public class User {
    private Integer id;
    private String username;
    private String password;
    private String phone;
    private String location;
    private Date last_time;
 
    set/get/toString
    
    }
}

//主方法
import com.java.druid.Utils;
import org.springframework.jdbc.core.JdbcTemplate;
 
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Scanner;
 
public class Main {
    protected static JdbcTemplate template = new JdbcTemplate(Utils.getDataSource());
 
    public static void main(String[] args) {
        //用户登录
        User user = Login.login();
        //日期格式化
        SimpleDateFormat pdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 
        Scanner sc = new Scanner(System.in);
        //判断用户实体类是否为空
        if (user != null) {
            System.out.println("欢迎"   user.getUsername()   "登录,上次登录时间为:"   pdf.format(user.getLast_time()) );
            template.update("update user set last_time = ? where username = ?",new Date(),user.getUsername());
            System.out.println("1.修改密码rn"   "2.查询表单");
 
            int num = sc.nextInt();
            switch (num) {
                case 1 :
                    Update.update(user);
                    break;
                case 2 :
                    Select.select();
                    break;
                default:
                    System.out.println("指令输入错误");
            }
        } else {
            System.out.println("登录失败!");
        }
    }
}

//登录
import org.springframework.jdbc.core.BeanPropertyRowMapper;
 
import java.util.Scanner;
 
public class Login {
    public static User login() {
        //从键盘键入账户和密码
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入用户名");
        String username = sc.nextLine();
        System.out.println("请输入密码");
        String password = sc.nextLine();
 
        //sql 语句
        String sql = "select * from user where username = ? and password = password(?)";
 
        //将查询结果封装为JavaBean
        User user = Main.template.queryForObject(sql,
                new BeanPropertyRowMapper<User>(User.class), username, password);
 
        return user;
    }
}

//修改密码
import java.util.Scanner;
 
public class Update {
    public static void update(User user) {
        //获取用户名
        String username = user.getUsername();
        //从键盘键入旧密码
        Scanner sc = new Scanner(System.in);
        while (true) {
            System.out.println("请输入新密码");
            String password = sc.nextLine();
            //sql
            String sql = "update user set password = password(?) where username = ?";
            //执行sql
            int i = Main.template.update(sql, password, username);
            //处理结果
            if (i > 0) {
                System.out.println("修改成功");
                return;
            } else {
                System.out.println("修改失败");
            }
        }
    }
}

//查询
import org.springframework.jdbc.core.BeanPropertyRowMapper;
 
import java.util.List;
 
public class Select {
    public static void select() {
        //sql
        String sql = "select * from user";
        //封装查询结果并返回
        List<User> list =  Main.template.query(sql, new BeanPropertyRowMapper<User>(User.class));
 
        for (User user : list) {
            System.out.println(user);
        }
    }
}

0 人点赞