提升查询效率的几种方式
1、连接池
2、缓存:第一次查询很慢,之后会查询的很快(用来做缓存的数据库有redis)
3、主键:主键所在的字段会自动分配一个索引,但索引会占据硬盘空间,一般只给常用作查询的字段加上索引,方便对字段进行快速查找
模拟一个缓存
案例:将students.txt中的数据放大1000倍插入到数据库中
public class MakeDataMYSQL {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(
new FileReader("D:\\BigData\\ideaProjects\\bd13\\data\\student.txt"));
String line;
while((line=br.readLine())!=null){//每条数据放大1000倍到mysql
String[] split = line.split(",");
String id = split[0];
String name = split[1];
String age = split[2];
String sex = split[3];
String clazz = split[4];
//插数据
Connection conn = JDBCUtil.getConn();
String sql="insert into students(id,name,age,sex,clazz) values (?,?,?,?,?)";
PreparedStatement ps = conn.prepareStatement(sql);
for (int i = 1; i <1000 ; i++) {//id不重复
ps.setString(1,id+i); //id=id+i (String+int做拼接)
ps.setString(2,name);
ps.setString(3,age);
ps.setString(4,sex);
ps.setString(5,clazz);
//增加数据 增加一行一行的数据
ps.addBatch();
}
//按块,按批执行语句
ps.executeBatch();
System.out.println("1000条数据插入成功");
ps.close();
conn.close();
}
br.close();
}
}
1、表现层
http://localhost:8080/selectbyid/?id=1500100002108
@RestController
public class UserController {
@RequestMapping("/selectbyid")
public String selectById(String id){
UserService userService = new UserService();
String s = userService.selectById(id);
return s;
}
}
2、业务逻辑层
public class UserService {
//增加缓存
//模拟一个缓存的list集合 arraylist set map
//适合做缓存的 是k:v结构的map
private static HashMap<String ,Students> map=new HashMap<String ,Students>();
public String selectById(String id){
/**
* 1.先查缓存
* 1.1有:直接返回数据
* 1.2没有:去数据库中查,并把结果保存到缓存
*/
//1.1有:直接返回数据
if(map.containsKey(id)){
return map.get(id).toString();
}
//1.2没有:去数据库中查,并把结果保存到缓存
UserDao userDao = new UserDao();
Students students = userDao.selectById(id);
if(students==null){
return "用户不存在";
}
map.put(students.getId(),students);
return students.toString();
}
}
3、持久层
public class UserDao {
public Students selectById(String id){
Students students=null;
String sql="select * from students where id=?";
try {
Connection conn = JDBCUtil.getConn();
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1,id);
ResultSet rs = ps.executeQuery();
if(rs.next()){
students = new Students();
students.setId(rs.getString("id"));
students.setName(rs.getString("name"));
students.setAge(rs.getString("age"));
students.setSex(rs.getString("sex"));
students.setClazz(rs.getString("clazz"));
}
rs.close();
ps.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
return students;
}
}