网站首页
Java
站长
开源
框架
理论
JS
Linux
DB
服务器
NET
生活
软件
PHP
其他
您的位置:首页 > Java > 使用JDBC查询是否存在某表或视图,按月动态生成表
使用JDBC查询是否存在某表或视图,按月动态生成表
2015-6-1    9828    0

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


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

上一篇: 如何下载秒拍、美拍等小众或者新兴网站的视频
下一篇: 使用 JdbcTemplate 动态创建表并添加数据
发表评论:
您的网名:
个人主页:
编辑内容: