首先注入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},不然会报错的!!