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

本文介绍了如何使用JDBC连接MySQL数据库,通过`getMetaData()`方法判断视图是否存在。如果不存在,代码将动态创建视图。示例代码展示了如何创建表结构,并在保存数据前检查表是否存在,若不存在则先创建。此外,还提到表名可以根据日期进行动态生成,以满足按月创建的需求。
摘要由CSDN通过智能技术生成

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

}

然后判断是有某表,如果没有,调用创建

/**

* 根据表名称创建一张表

* @param tableName

*/

public int createTable(String tableName){

StringBuffer sb = new StringBuffer("");

sb.append("CREATE TABLE `" + tableName + "` (");

sb.append("`id` int(11) NOT NULL AUTO_INCREMENT ,");

sb.append("`alertId` int(11) NULL DEFAULT NULL ,");

sb.append("`alertTime` int(11) NULL DEFAULT NULL ,");

sb.append("`alertLevel` int(11) NULL DEFAULT NULL ,");

sb.append("`deviceMark` int(11) NULL DEFAULT NULL ,");

sb.append("`carNo` int(11) NULL DEFAULT NULL ,");

sb.append("`updateTime` varchar(255) DEFAULT NULL ,");

sb.append("PRIMARY KEY (`id`)");

sb.append(") CHARACTER SET=utf8 COLLATE=utf8_general_ci;");

try {

jdbcTemplate.update(sb.toString());

return 1;

} catch (Exception e) {

e.printStackTrace();

}

return 0;

}

这两个方法可以公用,至于是按月还是按天还是按周,取决于你对表名称的生成

/**

* 保存

*/

@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;

}

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

最后:

由于近期大量小网站在未经同意情况下使用文章,现将我的博客地址公布如下,请您到ITEYE网站看原创,谢谢!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值