- 2023-06-01 13:31:19
- 6014 热度
- 0 评论
前面已经说了一个动态的根据当前时间创建表和插入数据的示例,那么如何进行动态的查询呢?
我写了这样一个公共方法,仅供参考!
这里需要传递两个时间间隔参数,根据时间间隔判断相差的月数,然后从起始时间开始递增月份,然后动态拼装表的名称,如果存在该表则标记需要查询
所有的SQL通过 union all 来连接,最后增加分页的参数,分页只适合MySQL数据库
当然这个示例也只是适合于按月份来存储的情况
代码并不是很复杂,希望大家还是通过代码来理解一下:
package com; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.List; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.jdbc.core.JdbcTemplate; /** * @说明 进行测试 * @author cuisuqiang * @version 1.0 * @since */ public class DbTest { private static ApplicationContext context = null; @SuppressWarnings("unchecked") public static void main(String[] args) { context = new ClassPathXmlApplicationContext("applicationContext.xml"); String sql = "select * from :TABLE_NAME"; String key = "nm_cpu_log"; String beginTime = "2012-1-1 12:12:12"; String endTime = "2014-12-1 12:12:12"; String formatkey = "yyyy_MM"; List list = getListFromEachTable(sql,key,beginTime,endTime,formatkey,1,100); if(null != list){ System.out.println(list.size()); }else{ System.out.println("没有数据!"); } } /** * 动态查询表数据 * @param sqlTemplate 要执行的单条SQL 其中表名称用 :TABLE_NAME 标识 * @param tableKey 表前缀,不包含和时间中间的 下划线 * @param dateBegin 开始时间 yyyy-MM-dd HH:mm:ss * @param dateEnd 结束时间 yyyy-MM-dd HH:mm:ss * @param dateFormat 时间格式化方式 * @param pageIndex 分页索引 从 1 开始 * @param pageCount 每页查询数量 无限制 * @return 模版查询直接返回 */ @SuppressWarnings("unchecked") public synchronized static List getListFromEachTable(String sqlTemplate, String tableKey, String dateBegin, String dateEnd, String dateFormat, int pageIndex, int pageCount) { List list = null; try { // 一共有多少需要执行的SQL List<String> sqlList = new ArrayList<String>(); JdbcTemplate jt = (JdbcTemplate) context.getBean("jdbcTemplate"); // 转为时间 Date dbegin = StringToDateTime(dateBegin); Date dend = StringToDateTime(dateEnd); // 相差的月数 int monthCount = calculateMonthIn(dend, dbegin); for (int i = 0; i <= monthCount; i++) { // 下 N 个月的时间 Date d = getNextMonth(dbegin, i); SimpleDateFormat format = new SimpleDateFormat(dateFormat); // 动态表名 String tableName = tableKey + "_" + format.format(d); // 如果有某表 if (getAllTableName(jt, tableName)) { System.out.println("存在表:" + tableName); // 替换名称获得SQL String sql = sqlTemplate.replace(":TABLE_NAME", tableName); sqlList.add(sql); } } // 实际要执行的SQL StringBuffer sqlGo = new StringBuffer(""); if (sqlList.size() > 0) { for (int i = 0; i < sqlList.size(); i++) { if (i == sqlList.size() - 1) { sqlGo.append(sqlList.get(i)); } else { sqlGo.append(sqlList.get(i) + " union all "); } } } if (sqlList.size() > 0) { // 增加分页 int cindex = (pageIndex - 1) * pageCount; sqlGo.append(" limit " + cindex + "," + pageCount); } if (!"".equals(sqlGo.toString())) { System.out.println("执行的SQL:" + sqlGo.toString()); // 执行查询 list = jt.queryForList(sqlGo.toString()); } } catch (Exception e) { e.printStackTrace(); list = null; } return list; } /** * 将传入的字符串按yyyy-MM-dd HH:mm:ss格式转换成对应的日期对象 * @param str 需要转换的字符串 */ public synchronized static Date StringToDateTime(String str) { String _pattern = "yyyy-MM-dd HH:mm:ss"; return StringToDate(str, _pattern); } /** * 将插入的字符串按格式转换成对应的日期对象 * @param str 字符串 * @param pattern 格式 */ public synchronized static Date StringToDate(String str, String pattern) { Date dateTime = null; try { if (str != null && !str.equals("")) { SimpleDateFormat formater = new SimpleDateFormat(pattern); dateTime = formater.parse(str); } } catch (Exception ex) { ex.printStackTrace(); } return dateTime; } /** * 两个时间相差的月数 * @param date1 * @param date2 * @return */ public static int calculateMonthIn(Date date1, Date date2) { Calendar cal1 = new GregorianCalendar(); cal1.setTime(date1); Calendar cal2 = new GregorianCalendar(); cal2.setTime(date2); int c = (cal1.get(Calendar.YEAR) - cal2.get(Calendar.YEAR)) * 12 + cal1.get(Calendar.MONTH) - cal2.get(Calendar.MONTH); return c; } /** * 获得下几个月的时间对象 * @param date * @param count * @return */ public static Date getNextMonth(Date date, int count) { Calendar c = Calendar.getInstance(); c.setTime(date); c.add(Calendar.MONTH, count); return c.getTime(); } /** * 查询数据库是否有某表 * @param jt * @param tableName * @return * @throws Exception */ @SuppressWarnings("unchecked") public static boolean getAllTableName(JdbcTemplate jt, String tableName) throws Exception { Connection conn = jt.getDataSource().getConnection(); ResultSet tabs = null; try { DatabaseMetaData dbMetaData = conn.getMetaData(); String[] types = { "TABLE" }; tabs = dbMetaData.getTables(null, null, tableName, types); if (tabs.next()) { return true; } } catch (Exception e) { e.printStackTrace(); } finally { tabs.close(); conn.close(); } return false; } }
代码仅供参考,注意实际应用。
注意这是一个系列的文章,注意前后几篇文章。
0 评论
留下评论
热门标签
- Spring(403)
- Boot(208)
- Spring Boot(187)
- Spring Cloud(82)
- Java(82)
- Cloud(82)
- Security(60)
- Spring Security(54)
- Boot2(51)
- Spring Boot2(51)
- Redis(31)
- SQL(29)
- Mysql(25)
- Dalston(24)
- IDE(24)
- mongoDB(22)
- MVC(22)
- JDBC(22)
- IDEA(22)
- Web(21)
- CLI(20)
- Alibaba(19)
- SpringMVC(19)
- Docker(17)
- SpringBoot(17)
- Git(16)
- Eclipse(16)
- Vue(16)
- JPA(15)
- Apache(15)
- ORA(15)
- Tomcat(14)
- Linux(14)
- HTTP(14)
- Mybatis(14)
- Oracle(14)
- jdk(14)
- OAuth(13)
- Nacos(13)
- Pro(13)
- XML(13)
- JdbcTemplate(13)
- JSON(12)
- OAuth2(12)
- Data(12)
- int(11)
- Myeclipse(11)
- stream(11)
- not(10)
- Bug(10)
- Hystrix(9)
- ast(9)
- maven(9)
- Map(9)
- Swagger(8)
- APP(8)
- Bit(8)
- API(8)
- session(8)
- Window(8)
- windows(7)
- too(7)
- HTML(7)
- Github(7)
- JavaMail(7)
- Cache(7)
- File(7)
- IntelliJ(7)
- mail(7)
- Server(6)
- nginx(6)
- jar(6)
- ueditor(6)
- ehcache(6)
- UDP(6)
- RabbitMQ(6)
- and(6)
- star(6)
- Excel(6)
- Log4J(6)
- pushlet(6)
- apt(6)
- Freemarker(6)
- read(6)
- WebFlux(6)
- JSP(6)
- Bean(6)
- error(6)
- are(5)
- SVN(5)
- for(5)
- DOM(5)
- Sentinel(5)
- the(5)
- JWT(5)
- rdquo(5)
- PHP(5)
- Struts(5)
- string(5)
- script(5)