Spring Boot Java JdbcTemplate实现数据库表和字段的动态添加、编辑、删除

基于JdbcTemplate来动态操作数据库的表结构:

/**
 * Created by WangBaBa on 2023/9/12.
 */
@Service
public class TableService {
    @Autowired
    JdbcTemplate jdbcTemplate;

    /**
     * 返回所有表
     * @return
     */
    @Transactional
    public Result getTable(){
        try {
            String SQL = "SELECT * FROM 表";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(SQL);
            return Result.ok("查询成功",list);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败");
        }
    }

    /**
     * 返回表格字段
     * @return
     */
    @Transactional
    public Result getTableFields(String table){
        try {
            String SQL = "SELECT * FROM 表 WHERE id = ?";
            List<Map<String, Object>> list = jdbcTemplate.queryForList(SQL, table);
            return Result.ok("查询成功",list);

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("查询失败");
        }
    }

    /**
     * 创建(编辑)表
     * @return
     */
    @Transactional
    public Result addTable(String ID ,String oldtablename, String tablename, String alname, String tabletype){
        try {
            // 判断数据库是否存在数据
            if(ID == ""){
                // 添加ID
                Map<String, Object> count = jdbcTemplate.queryForMap("SELECT MAX(ID) FROM 表");
                int id =  1;
                if(count.get("") != null){
                    id =  Integer.parseInt(count.get("").toString()) + 1;
                }
                // 添加数据
                String SQL = "INSERT INTO 表 VALUES (?, ?, ?, ?, ? ,NULL ,NULL )";
                jdbcTemplate.update(SQL, id, tablename, alname, tabletype, "0");

                // 创建表
                String SQL1 = "CREATE TABLE " + tablename + " (ID int not null PRIMARY KEY)";
                jdbcTemplate.execute(SQL1);

                System.out.println("创建表:" + id);
                return Result.ok("创建成功");
            } else {
                // 更新数据
                String SQL = "UPDATE 表 SET 表名=?,别名=?,类型=? WHERE ID=?";
                int res = jdbcTemplate.update(SQL, tablename, alname, tabletype, ID);

                // 修改表名
                String SQL1 = "EXEC sp_rename " + oldtablename + "," + tablename;
                jdbcTemplate.execute(SQL1);

                System.out.println("表名:" + oldtablename + "  修改为:" + tablename);
                return Result.ok("编辑成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("编辑失败");
        }
    }

    /**
     * 删除表
     * @return
     */
    @Transactional
    public Result deleteTable(String tablename){
        try {
            // 删除数据
            String SQL = "DELETE FROM 表 WHERE 表名=?";
            jdbcTemplate.update(SQL, tablename);

            // 删除表
            String SQL1 = "DROP TABLE " + tablename;
            jdbcTemplate.execute(SQL1);

            System.out.println("删除表:" + tablename);
            return Result.ok("删除成功");

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败");
        }
    }

    /**
     * 创建(编辑)字段
     * @return
     */
    @Transactional
    public Result addFields(String ID , String oldfieldname, String fieldname, String alname, String fieldtype, String form, String unit, String type, String table, String config, String preset){
        try {
            // 判断数据库是否存在数据
            if(ID == ""){
                // 添加ID
                Map<String, Object> count = jdbcTemplate.queryForMap("SELECT MAX(ID) FROM 表");
                int id =  1;
                if(count.get("") != null){
                    id =  Integer.parseInt(count.get("").toString()) + 1;
                }
                // 添加字段
                String SQL = "INSERT INTO 表 VALUES (?, ?, ?, ?, ? ,?, ?, ?, ?, ? )";
                jdbcTemplate.update(SQL, id, fieldname, alname, fieldtype, form, unit, type, table, config, preset);

                // 添加表字段
                String SQL1 = "ALTER TABLE " + table + " ADD " + fieldname + " " + fieldtype;
                jdbcTemplate.execute(SQL1);

                System.out.println("创建字段:" + id);
                return Result.ok("创建成功");
            } else {
                // 更新数据
                String SQL = "UPDATE 表 SET 字段名=?,别名=?,字段类型=?,形态=?,单位=?,类型=?,配置=?,预设值=? WHERE ID=?";
                jdbcTemplate.update(SQL, fieldname, alname, fieldtype, form, unit, type, config, preset, ID);

                // 修改字段名 exec sp_rename '表.aa','bb';
                String SQL1 = "EXEC sp_rename \"" + table + "." + oldfieldname + "\",\"" + fieldname + "\"";
                jdbcTemplate.execute(SQL1);

                // 修改字段类型 ALTER TABLE 表 ALTER COLUMN 字段 nvarchar(100)
                String SQL2 = "ALTER TABLE " + table + " ALTER COLUMN " + fieldname + " " + fieldtype;
                jdbcTemplate.execute(SQL2);

                System.out.println("字段:" + oldfieldname + "  修改为:" + fieldname + "  类型:" + fieldtype);
                return Result.ok("编辑成功");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("编辑失败");
        }
    }

    /**
     * 删除字段
     * @return
     */
    @Transactional
    public Result deleteFields(String table, String fieldname){
        try {
            // 删除数据
            String SQL = "DELETE FROM 表 WHERE 字段名=? AND 所属表=?";
            jdbcTemplate.update(SQL, fieldname, table);

            // 删除表字段
            String SQL1 = "ALTER TABLE " + table + " DROP COLUMN " + fieldname;
            jdbcTemplate.execute(SQL1);

            System.out.println("表:" + table + " 删除字段:" + fieldname);
            return Result.ok("删除成功");

        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("删除失败");
        }
    }

}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot中创建定时任务可以使用注解 `@EnableScheduling` 开启定时任务的支持。首先,在启动类上添加 `@EnableScheduling` 注解。接下来,创建一个定时任务的类,并添加 `@Component` 注解,使其成为Spring管理的Bean。 在定时任务类中,可以使用`@Scheduled`注解来标注具体的定时方法,以指定任务的执行时间。`@Scheduled`注解支持多种时间达方式,如固定延迟时间、固定间隔时间、Cron达式等。 在配合数据库动态执行定时任务的场景中,可以在任务方法中读取数据库中的配置信息,来动态设定定时任务的执行时间。具体实现方式如下: 1. 首先,在数据库中创建一个定时任务配置,包含任务名称、任务执行时间等字段。 2. 在定时任务类中注入数据源,并使用JdbcTemplate或者MyBatis等方式来访问数据库。 3. 创建一个方法,通过查询数据库获取定时任务的执行时间,并将执行时间作为参数传递给`@Scheduled`注解。 4. 使用`@Scheduled`注解标注这个方法,使其成为定时执行的任务。 以下是一个示例代码: ```java @Component public class MyScheduledTask { @Autowired private JdbcTemplate jdbcTemplate; @Scheduled(fixedDelay = 5000) // 每隔5秒执行一次 public void executeTask() { // 从数据库读取任务执行时间 String scheduleTime = jdbcTemplate.queryForObject("SELECT schedule_time FROM task_config WHERE task_name = 'myTask'", String.class); // 将任务执行时间格式化为Cron达式 String cronExpression = convertToCronExpression(scheduleTime); // 执行任务 System.out.println("执行定时任务..."); // 更新数据库中的任务执行状态等相关信息 jdbcTemplate.update("UPDATE task_config SET last_execute_time = ?, status = 'completed' WHERE task_name = 'myTask'", new Date()); } private String convertToCronExpression(String scheduleTime) { // 将任务执行时间格式转换为Cron达式的逻辑 // ... } } ``` 以上代码中,定时任务类`MyScheduledTask`中的`executeTask`方法使用`@Scheduled`注解标注,将定时任务的执行时间动态设定为从数据库中读取的值。执行任务的代码可以根据具体的业务需求进行编写。 需要注意的是,在使用数据库动态设定定时任务的执行时间时,需要在适当的时候更新数据库中相关的任务信息,以便下次执行任务时能够获取到最新的执行时间。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

王八八。

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值