时间段1
stime: 2018-02-11 22:37:36 //开始时间
etime: 2019-06-07 22:38:15 //结束时间
时间段2
stime: 2020-02-11 22:37:36
etime: 2021-06-07 22:38:15
时间段3
stime: 2022-02-11 22:37:36
etime: 2023-06-07 22:38:15
public class Time { private static HashMap<String, String> map = new HashMap<>(); public static Map time(String time1, String time2) { List<String> list = new ArrayList<String>(); Pattern pattern = Pattern.compile("[0-9]{4}[-][0-9]{1,2}[-][0-9]{1,2}[ ][0-9]{1,2}[:][0-9]{1,2}[:][0-9]{1,2}"); Matcher matcher = pattern.matcher("33444,2014-02-11 22:37:36,202019-06-07 22:38:15," + "mac,ertc,wwsc,33444,2020-02-11 22:37:36,2021-06-07 22:38:15,33444,2022-02-11 22:37:36,2023-06-07 22:38:15"); String time = ""; while (matcher.find()) { time = matcher.group(); list.add(time); } for (int i = 0; i < list.size(); i++) { if (i % 2 == 0) { String time11 = list.get(i); time1 = "('" + time11 + "')"; } else { String time22 = list.get(i); time2 = "('" + time22 + "')"; } map.put(time1, time2); } return map; } public static void main(String[] args) { String time1 = ""; String time2 = ""; testQueryAll(time1, time2); } @Test public static String testQueryAll(String time1, String time2) { Map time = time(time1, time2); Set<String> set = map.keySet(); Iterator<String> it = set.iterator(); // 1.注册驱动 try { Class.forName("com.mysql.jdbc.Driver"); // 2.设置参数 String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=GMT%2B8&useSSL=false"; String username = "root"; String password = "root"; // 3.获取连接对象 Connection conn = DriverManager.getConnection(url, username, password); // 4.获得执行sql语句的对象 Statement stmt = conn.createStatement(); // 5.编写SQL语句 String sql = ""; while (it.hasNext()) { String beginTime = it.next(); String eTime = map.get(beginTime); sql = "select * from scores where adress like '%北%' " + " and name like '%张%' and starttime < " + eTime + " and starttime > " + beginTime; } // 6.执行sql语句 ResultSet rs = stmt.executeQuery(sql); // 7.处理结果集 while (rs.next()) { String name = rs.getString(2); String score = rs.getString(3); System.out.println("姓名:" + name + ",成绩:" + score); } //8.释放资源 if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } catch (Exception e) { e.printStackTrace(); } return ""; } }