将sql语句中的表名加表前缀

该博客介绍了一个Java工具类,用于在SQL的`INSERT INTO`语句中添加表名前缀。通过定义一个常量匹配规则,实现了灵活处理`INSERT INTO`与表名之间的不确定空格数,并使用`SwitchStringUtil`类的`switchStringByRule`方法进行替换操作,从而达到增加表前缀的目的。
摘要由CSDN通过智能技术生成

将sql语句中的表名加表前缀

问题描述

将 insert into table (item1, item2, itsm3) values (value1, value2, value3) 语句中的表名加前缀,但是insert 与into,into 与table之间的空格数量不确定到底有多少

实现方案

​ 利用正则表达式进行替换

创建字符串转换工具类

package com.wy.mycode.algorithm.string;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author HelloWorld
 * @create 2022/6/25 08:50
 * @email helloworld.dng@gmail.com
 */
public class SwitchStringUtil {

    /**
     * @description 按指定规则替换字符传
     * @author HelloWorld
     * @create 2022/6/25 08:55
     * @param str 待转换的字符串
     * @param rule 转换规则
     * @param target 转换子串
     * @return java.lang.String
     */
    public String switchStringByRule(String str, String rule, String target) {
        Pattern pattern = Pattern.compile(rule);
        Matcher matcher = pattern.matcher(str);
        return matcher.replaceFirst(target);
    }
}

实现按规则增加表名前缀的方法

package com.wy.mycode.algorithm.string;

/**
 * @author HelloWorld
 * @create 2022/6/25 10:09
 * @email helloworld.dng@gmail.com
 */
public class AlterTableName {
    /** 匹配sql语句中的 insert into  规则*/
    private static final String SWITCH_RULE = "insert \\s*into \\s*";

    /**
     * @description
     * @author HelloWorld
     * @create 2022/6/25 10:24
     * @param sql 需要转换的sql
     * @param prefix 表名前缀
     * @return java.lang.String
     */
    private String doAlterTableName(String sql, String prefix) {
        SwitchStringUtil switchStringUtil = new SwitchStringUtil();
        String target = "insert into " + prefix;
        return switchStringUtil.switchStringByRule(sql, SWITCH_RULE, target);
    }

    public static void main(String[] args) {
        String str = "insert    into     table (item1, item2) values (value1, value2)";
        AlterTableName alterTableName = new AlterTableName();
        System.out.println(alterTableName.doAlterTableName(str, "PD_"));
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值