Java小强个人技术博客站点    手机版
当前位置: 首页 >> Java >> 使用JDBC查询是否存在某表或视图,按月动态生成表

使用JDBC查询是否存在某表或视图,按月动态生成表

98700 Java | 2015-6-1

查询数据库是否有某表的存在,主要用的就是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;
}


我的格式化方法决定了是按照月来进行生成,如果有直接保存,如果没有,先生成再保存!

推荐您阅读更多有关于“ jdbc 视图 动态建表 按月 ”的文章

上一篇:如何下载秒拍、美拍等小众或者新兴网站的视频 下一篇:使用 JdbcTemplate 动态创建表并添加数据

猜你喜欢

发表评论: