动态建表并插入数据
Service层根据解析到的数据在Mysql数据库中动态建表并插入数据
以Easy Excel解析得到的文件为例
@Slf4j
@Service
public class ExcelImportServiceImpl implements ExcelImportService {
@Autowired
private ExcelImportDao dao;
@Value("${source.url}")
private String DB_URL;
@Value("${source.name}")
private String USER;
@Value("${source.pwd}")
private String PASS;
//filePath:文件存储绝对路径,tableName:创建的表名
@Override
public Result importExcel(String filePath,String tableName) {
// 首先创建一个ExcelImportUtilOne的实例,用于处理Excel文件的导入相关操作
ExcelImportUtilOne excelImportUtil = new ExcelImportUtilOne(filePath);
// 如果ExcelImportUtilOne实例获取的结果为0,表示可能在读取Excel文件等前期操作中有问题,直接返回0表示导入失败
if(excelImportUtil.getResult()==0)
return Result.error();
//表数据
List<Map<String, String>> dataList = excelImportUtil.getDataList();
//表字段
String[] columns = excelImportUtil.getColumns();
//动态建表外部方法
dynamicCreatTable(tableName,columns);
ArrayList<String> fieldList = new ArrayList<>(Arrays.asList(columns));
//动态插入数据
dao.dynamicSave(tableName,fieldList,dataList);
return Result.ok();
}
//动态建表方法
private void dynamicCreatTable(String tableName,String[] columns){
StringBuilder sql = new StringBuilder("CREATE TABLE ");
sql.append(tableName).append(" (");
sql.append("id BIGINT PRIMARY KEY AUTO_INCREMENT,");
for (int i = 0; i < columns.length; i++) {
sql.append(columns[i]).append(" VARCHAR(255)");
if (i < columns.length - 1) {
sql.append(", ");
}
}
sql.append(");");
String statement = sql.toString();
// 创建Connection对象
// JDBC连接参数
String url = DB_URL;
String username = USER;
String password = PASS;
try (Connection connection = DriverManager.getConnection(url, username, password)) {
// 创建Statement对象
// Statement psStatement = connection.createStatement();
PreparedStatement psStatement = connection.prepareStatement(statement, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
// 在此处执行更新SQL语句
psStatement.executeUpdate();
// 关闭Statement
// resultSet.close();
psStatement.close();
} catch (SQLException e) {
log.error("建表失败", e);
}
}
}
Mapper层
@Mapper
public interface ExcelImportDao {
//动态插入数据
void dynamicSave(String tableName, ArrayList<String> fieldList, List<Map<String, String>> dataList);
}
xml文件
<mapper namespace="net.srt.system.dao.ExcelImportDao">
<insert id="dynamicSave">
INSERT INTO ${tableName}(
<foreach collection="fieldList" item="fieldEach" separator=",">
${fieldEach}
</foreach>
) VALUES
<foreach collection="dataList" item="dataEach" separator=",">
(
<foreach collection="fieldList" item="fieldEach" separator=",">
#{dataEach.${fieldEach}}
</foreach>
)
</foreach>
</insert>
</mapper>
