要求:以学生-成绩为数据模型,使用jsonb类型存储数据,在PG上进行数据库建模,写一web程序能够实现两门课的成绩添加和查询操作。并加上redis的使用。
使用pgAdmin4进行数据库的创建并检测:
这之后在存储入数据的时候可以使用pgAdmin进行检测
create table table1(
name varchar primary key,
score json
)
/*
lilei, math:80、chinese:90、total:170
hanmm, sport:90、eng:90、total:180
*/
insert into table1 values('lilei','{"math":80,"chinese":90,"total":170}')
insert into table1 values('hanmm','{"sport":90,"eng":90,"total":180}')
/*
查询lilei的math成绩
查询每位同学的总成绩
查询数学成绩考了80的同学
查询选了体育的同学
*/
select score->'math' as lilei的math成绩 from table1 where name='lilei';
select score->'total' as 总成绩 from table1
select name from table1 where score->>'math' = '80'
select name from table1 where score::jsonb?'sport'
连接pgSQL和redis与之前学习的SQLserver一样,需要jdbc,必须先进行导入(导入的方式有多种,使用Eclipse的build path或者是直接放在tomcat下的lib,取决于你tomcat的服务器的设置)
先创建servlet:
1.connect.Java:
redis数据库与pgSQL数据库都是非关系型数据库,redis数据库是将数据存储在内存中的缓存,所以数据的读取会更快,使用的是key-value的形式进行的存储。
这里使用redis和pg的关系是:在每次查询数据的时候,先查询redis数据库的key值,也就是数据库中的学生id,如果存在,直接调用redis中的学生成绩数据,如果没有 ,就从pgsql中查询并调用,在调用的同时将此条数据的学生id作为key值,将数据库中的json文件解析出来的时候存储为hashmap并将此作为value值,存储到redis中,下次调用的时候直接从redis中拿
package CBw.connect;
import java.sql.*;
import java.util.Map;
import java.util.HashMap;
import javax.servlet.*;
import redis.clients.jedis.Jedis;
public class connect {
//连接数据库
private Connection connect() {
String url = "jdbc:postgresql://localhost:5432/postgres";
String user = "postgres";
String password = "123456";
Connection conn = null;
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//插入学生的数据
public boolean insertInfo(String id,String name, String course1, String course1_score, String course2,String course2_score) throws SQLException {
Connection conn = connect();
PreparedStatement ps = null;
ResultSet rs = null;
System.out.println(id+" "+name);
String sql = "select id from stu_score where id = ?;";
ps = conn.prepareStatement(sql);
ps.setInt(1, Integer.parseInt(id));
rs = ps.executeQuery();
if(rs.next()) {
return false;
}
int t_score1=Integer.parseInt(course1_score);
int t_score2=Integer.parseInt(course2_score);
int t_score=t_score1+t_score2;
sql = "insert into stu_score values(?, ?,"+
" '{\""+ course1+"\":"+course1_score+
",\"