jsp连接pgSQL+redis(初学者简单使用)

本文档介绍了如何使用jsp连接pgSQL数据库,利用jsonb类型存储学生-成绩数据模型,并实现成绩的增删查改。同时,结合redis缓存提升查询效率,当redis中无数据时回退到pgSQL查询。详细步骤包括数据库建模、servlet创建、异常处理及页面交互。总结了操作中的问题和改进空间。
摘要由CSDN通过智能技术生成

要求:以学生-成绩为数据模型,使用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+
				",\"
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值