查询数据库是否有某表的存在,主要用的就是Connection对象对元数据的操作,代码很简单,贴出来大家参考。
/** * 查询数据库是否有某表 * @param cnn * @param tableName * @return * @throws Exception */ @SuppressWarnings("unchecked") public boolean getAllTableName(String tableName) throws Exception { Connection conn = jdbcTemplate.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; }
这两个方法可以公用,至于是按月还是按天还是按周,取决于你对表名称的生成。
/** * 保存 */ @Override public int saveAlertMessLog(AlertMessLog alertMessLog) { SimpleDateFormat format = new SimpleDateFormat("yyyy_MM"); String tableName = "nm_alertmesslog_" + format.format(new Date()); try { boolean isHave = getAllTableName(tableName); if(isHave){ return saveObject(alertMessLog,tableName); }else{ if(createTable(tableName) == 1){ return saveObject(alertMessLog,tableName); } } } catch (Exception e) { e.printStackTrace(); } return 0; }
我的格式化方法决定了是按照月来进行生成,如果有直接保存,如果没有,先生成再保存!
Java小强
未曾清贫难成人,不经打击老天真。
自古英雄出炼狱,从来富贵入凡尘。
发表评论: