java判断某个表是否存在,如果不存在,则新建这个表

首先注入JdbcTemplate

<bean id = "jdbcTemplate" class = "org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref = "dbcpDataSource"></property>
    </bean>

使用java判断表是否存在,如果不存在,则使用java创建

public boolean isTableExistEntrust(String tableName) throws SQLException{
		Statement stmt=null;
		 boolean result = false;
		 java.sql.Connection connection = null;
		try {
			 DataSource dataSource = jdbcTemplate.getDataSource();
			 connection = dataSource.getConnection();
			 DatabaseMetaData meta = connection.getMetaData();
			 java.sql.ResultSet tables = meta.getTables (null, null, tableName, null);
			 stmt=connection.createStatement(); 
			 if (tables.next()) {
	             result = true; 
	         }else {
	        	System.out.println("此表不存在,创建");
	        	String SQL="CREATE TABLE "+tableName+" 建表语句";
				stmt.execute(SQL);
				result = true; 
			}
		} catch (Exception e) {
            e.printStackTrace ();
		}finally {
			if(connection !=null) {
				connection.close();
			}
		}
		return result;
	}

注意点:
我这里需要每天创建一个表,所以是以日期命名的

Calendar c = Calendar.getInstance();
		int year = c.get(Calendar.YEAR);
		int month = c.get(Calendar.MONTH)+1;
		int day = c.get(Calendar.DAY_OF_MONTH);
		String tableNameTurnover = "trade$order_turnover_backup" + "_" + year + "_" + month + "_" + day;  
		String tableNameEntrust = "trade$order_entrust_backup" + "_" + year + "_" + month + "_" + day; 

以上是表明构成,创建表语句将表明以参数的形式传入
参数 形式 是${tableName} ,注意不是#{orderId},不然会报错的!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值