public class ColumnVo {
private String columnName;//字段名称
private String columnType;//字段类型 "整数","小数","字符串","时间"
private Integer columnSize;//字段大小
private Boolean isNullable;//是否可为空
private Boolean isPrimary;//是否主键
private String remarks;//字段注释
}
public void addCustomTable(Connection connection, String tableName,
String tableRemarks, List<ColumnVo> columnVos) throws Exception {
if (tableName != null && tableRemarks != null && !CollectionUtils.isEmpty(columnVos)) {
//判断表名是否重复
ResultSet tables = connection.getMetaData().getTables(null, null, tableName, new String[]{"TABLE"});
if (tables.next()) {
throw new Exception("该表名已存在,请重新输入!");
}
tables.close();
//调用下方的生成建表语句的接口
String sql = getMySqlCreate(tableName, tableRemarks, columnVos);
Statement statement = connection.createStatement();
statement.execute(sql);
connection.close();
} else {
throw new Exception("新建表方法参数空值异常");
}
}
生成MySql的建表语句接口
//生成MySql的建表语句接口
public String getMySqlCreate(String tableName, String tableRemarks, List<ColumnVo> columnVos) {
StringBuffer sqlBuffer = new StringBuffer();
sqlBuffer.append("create table " + tableName + " (");
for (int i = 0; i < columnVos.size(); i++) {
ColumnVo columnVo = columnVos.get(i);
String columnName = columnVo.getColumnName();
String columnType = columnVo.getColumnType();
Integer columnSize = columnVo.getColumnSize();
if ("整数".equals(columnType)) {
sqlBuffer.append(columnName + " int " + "(" + columnSize + ") ");
} else if ("小数".equals(columnType)) {
sqlBuffer.append(columnName + " double ");
} else if ("字符串".equals(columnType)) {
sqlBuffer.append(columnName + " varchar " + "(" + columnSize + ") ");
} else if ("时间".equals(columnType)) {
sqlBuffer.append(columnName + " datetime ");
}
Boolean isPrimary = columnVo.getPrimary();
String primary = "";
if (isPrimary != null && isPrimary) {
primary = " primary key ";
}
Boolean isNullable = columnVo.getNullable();
String nullable = "";
if (isNullable != null && !isNullable) {
nullable = " not null ";
}
String remarks = columnVo.getRemarks();
sqlBuffer.append(primary + nullable + " comment '" + remarks + "',");
}
String s = sqlBuffer.toString();
String sql = s.substring(0, s.length() - 1) + ") COMMENT='" + tableRemarks + "'";
return sql;
}