linwe
2024-05-29 c10d6358b9f014375a13821465bc978d0c0da22e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package org.springblade.common.utils;
 
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class SQLParseUtils {
 
    public static String parseSQLType(String sql){
        if (sql==null){
            return null;
        }
        String type = sql.split(" ")[0];
        if (type.equalsIgnoreCase("INSERT")){
            return "INSERT";
        } else if (type.equalsIgnoreCase("UPDATE")) {
            return "UPDATE";
        } else if (type.equalsIgnoreCase("DELETE")) {
            return "DELETE";
        }else {
            return null;
        }
    }
 
    public static String getTableName(String sql) {
 
        String tableName = null;
        // 正则表达式匹配 INSERT、UPDATE 和 DELETE 语句
        String regex = "(?i)(?:INSERT\\s+INTO|UPDATE|DELETE\\s+FROM)\\s+(\\w+)";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(sql.trim());
        if (matcher.find()) {
            tableName = matcher.group(1);
        }
        return tableName;
    }
    public static void main(String[] args) {
        String tableName = getTableName("INSERT INTO orders (customer_id, product_id, quantity) VALUES (789, 123, 5)");
        System.out.println(tableName);
    }
 
}