Java解析insert语句中values的每一个值

insert语句是必须包含vales关键字(就我的认知),insert语句示例:

<1>. insert into test2021 values('a');

<2>.  insert into test2021 values('A', 'B', 'C',  4,  '你好, 我是某某某, 你是');

怎么使用Java获得insert语句中values的每一个值呢?

首先我们还是比较容易将insert语句从values关键字分为两段。

得到最后一段即包含有插入值的,('A', 'B', 'C', 4, '你好, 我是某某某, 你是');替换掉左右括号()和分号;

剩下'A', 'B', 'C',  4, '你好, 我是某某某, 你是'

我们再用.split(",")分割成数据。这里需要注意一个问题,当插入的值里面有道号,时这样是有问题的,

比如insert语句示例2中的'你好, 我是某某某, 你是'本来是一句话,会因为.split(",")分离了,所以我们就要处理这种情况

代码如下:

    public static void main(String[] args) {
        String testStr = "'A', 'B', 'C',  4, '你好, 我是某某某, 你是'";
        getValue(testStr);
        
    }

    public static void getValue(String testStr) {
        String[] strList = testStr.split(",");
        String columnValue = "";
        
        for (int i = 0; i < strList.length; i++) {            
            columnValue = strList[i];
            int startIndex = 0;
            int endIndex = 0;
            if (strList[i].trim().startsWith("'")) {
                startIndex = i;
                endIndex = i;
                int count = 0;
                while (true) {
                    count++;
                    if (endIndex < strList.length - 1) {
                        if (strList[++endIndex].contains("'")) {
                            if (strList[endIndex].trim().startsWith("'")) {
                                break;
                            }
                        } else {
                            if (strList[startIndex].trim().endsWith("'")) {
                                break;
                            }
                        }
                    }
                    if (++endIndex == strList.length) {
                        if (strList[(endIndex - 1) - 1].trim().endsWith("'")) {
                            break;
                        } else {
                            if (!strList[endIndex - 1].trim().startsWith("'")) {
                                ++endIndex;
                                break;
                            }
                        }
                    }
                    
                    // 防止死循环
                    if (count == 1001) {
                        break;
                    }
                }
                System.out.println("count=" + count);
            }
            
            if (endIndex - 1 > startIndex) {
                for (int j = startIndex + 1; j < endIndex - 1; j++) {
                    columnValue = columnValue + "," + strList[j];
                }
                
                // 跳过合并的,计算为(endIndex - 1)再减去for循环i自增的1
                i = (endIndex - 1) - 1;
            }
            System.out.println("value=" + columnValue);
        }
    }

这样columnValue就会得到原来的值。

更新--2021-10-27

以上的方法是有bug,对于一些特殊的value还是会识别不出来,所以我决定换一个思路去获取insert语句中values的每个值。以下是Java代码

    public static List<String> getTableColumnValueByMatchingSingleQuotes(String[] targetArray) {
        List<String> tableColumnValueList = new ArrayList<>();
        String columnValue = "";
        for (int i = 0; i < targetArray.length; i++) {
            columnValue = targetArray[i];
            int startIndex = i;
            int endIndex = i;
            boolean result = judgeMatchingSingleQuotes(columnValue);
            System.out.println(columnValue + " result: " + result);
            
            // 逻辑处理
            if (!result) {
                // false
                endIndex = getMatchingSingleQuotesIndex(targetArray, ++i);
            }
            
            if (endIndex != startIndex && endIndex != -999) {
                for (int j = startIndex + 1; j <= endIndex; j++) {
                    columnValue = columnValue + "," + targetArray[j];
                }
                // Set i = endIndx
                i = endIndex;
            }
                        
            System.out.println("column value = " + columnValue);
            tableColumnValueList.add(columnValue);
        }
        
        return tableColumnValueList;
    }
    
    public static int getMatchingSingleQuotesIndex(String[] targetArray, int startIndex) {
        for (int i = startIndex; i < targetArray.length; i++) {
            boolean result = judgeMatchingSingleQuotes(targetArray[i]);
            if (result) {
                ++startIndex;
            } else {
                return startIndex;
            }
        }
        
        return -999; // default value
    }
    
    /**
     * Judge single quotes is matching or not
     * 
     * @param target strings that need to count single quotes
     * @return if the count of single quotes is singular, return false, otherwise return true
     */
    public static boolean judgeMatchingSingleQuotes(String target) {
        char[] chars = target.toCharArray();
        int quotesCount = 0;
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '\'') {
                ++quotesCount;
            }
        }
        return quotesCount % 2 == 0;
    }

测试代码: 

public static void main(String[] args) {
        String str = "'ABCD', 'EFG','HIJK','LMNOPQ','abc ''def (ghij, ''klmn'', ''kokoio'')','uuywe','fasf','N'";
        
        getTableColumnValueByMatchingSingleQuotes(str.split(","));
    }

简单说一下思路,insert语句里的每个value如果是字符,都会带有单引号而且是成对的,利用这个特点去判断分割(str.split(","))后每个元素所包含的单引号是否匹配即成对,不匹配就记录当前字符的startIndex,再去查找下一个不匹配的字符并记录endIndex,这个startIndex到endIndex(包括本身)合起来就是一个完整的value。结合代码看容易理解点,有什么问题都可以在评论处提问。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
将 SQL 文件INSERT INTO 语句转化为 Java 对象,一般需要以下步骤: 1. 根据 SQL 文件的表结构,创建对应的 Java 类,每个字段对应一个属性,并为每个属性提供相应的 getter/setter 方法。 2. 解析 SQL 文件,将 INSERT INTO 语句的数据解析出来,并组装成一个个对应的 Java 对象。 3. 将解析得到的 Java 对象进行持久化存储,可以使用 JDBC 或者 ORM 框架(如 Hibernate、MyBatis 等)来实现。 举个例子,假设有以下 SQL 语句: ```sql INSERT INTO user (id, name, age) VALUES (1, 'Alice', 20); ``` 则可以创建一个名为 User 的 Java 类,代码如下: ```java public class User { private int id; private String name; private int age; // getter/setter 方法省略 public User(int id, String name, int age) { this.id = id; this.name = name; this.age = age; } } ``` 然后解析 SQL 文件,将 INSERT INTO 语句的数据解析出来并组装成对应的 Java 对象: ```java String sql = "INSERT INTO user (id, name, age) VALUES (1, 'Alice', 20);"; String[] fields = sql.split("\\(").split("\\)").split(","); // 获取表字段列表 String[] values = sql.split("VALUES \\(").split("\\)").split(","); // 获取字段列表 Map<String, String> map = new HashMap<>(); for (int i = 0; i < fields.length; i++) { map.put(fields[i].trim(), values[i].trim()); } User user = new User(Integer.parseInt(map.get("id")), map.get("name"), Integer.parseInt(map.get("age"))); ``` 最后使用 JDBC 或者 ORM 框架将 Java 对象进行持久化存储。如果使用 JDBC,可以使用 PreparedStatement 来执行 INSERT 语句,例如: ```java Connection conn = DriverManager.getConnection(url, username, password); PreparedStatement ps = conn.prepareStatement("INSERT INTO user (id, name, age) VALUES (?, ?, ?)"); ps.setInt(1, user.getId()); ps.setString(2, user.getName()); ps.setInt(3, user.getAge()); ps.executeUpdate(); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值