|
@@ -146,51 +146,29 @@ public class SqlExecuteTask {
|
|
|
* @return
|
|
|
*/
|
|
|
public static String extractTableName(String sql) {
|
|
|
- String upperCase = sql.toUpperCase().replaceAll("\"", "");
|
|
|
-
|
|
|
- Pattern pattern = null;
|
|
|
- Matcher matcher = null;
|
|
|
-
|
|
|
- // 匹配 SELECT 语句中的表名
|
|
|
- pattern = Pattern.compile("(?i)\\bFROM\\s+([\\w.]+)");
|
|
|
- matcher = pattern.matcher(upperCase);
|
|
|
- if (matcher.find()) {
|
|
|
- return matcher.group(1);
|
|
|
- }
|
|
|
-
|
|
|
- // 匹配 INSERT 语句中的表名
|
|
|
- pattern = Pattern.compile("(?i)\\bINTO\\s+([\\w.]+)");
|
|
|
- matcher = pattern.matcher(upperCase);
|
|
|
- if (matcher.find()) {
|
|
|
- return matcher.group(1);
|
|
|
- }
|
|
|
-
|
|
|
- // 匹配 UPDATE 语句中的表名
|
|
|
- pattern = Pattern.compile("(?i)\\bUPDATE\\s+([\\w.]+)");
|
|
|
- matcher = pattern.matcher(upperCase);
|
|
|
- if (matcher.find()) {
|
|
|
- return matcher.group(1);
|
|
|
- }
|
|
|
-
|
|
|
- // 匹配 DELETE 语句中的表名
|
|
|
- pattern = Pattern.compile("(?i)\\bDELETE\\s+FROM\\s+([\\w.]+)");
|
|
|
- matcher = pattern.matcher(upperCase);
|
|
|
- if (matcher.find()) {
|
|
|
- return matcher.group(1);
|
|
|
- }
|
|
|
-
|
|
|
- // 匹配 CREATE 语句中的表名
|
|
|
- pattern = Pattern.compile("(?i)\\bCREATE\\s+TABLE\\s+([\\w.]+)");
|
|
|
- matcher = pattern.matcher(upperCase);
|
|
|
- if (matcher.find()) {
|
|
|
- return matcher.group(1);
|
|
|
- }
|
|
|
-
|
|
|
- // 匹配 DROP 语句中的表名
|
|
|
- pattern = Pattern.compile("(?i)\\bDROP\\s+TABLE\\s+([\\w.]+)");
|
|
|
- matcher = pattern.matcher(upperCase);
|
|
|
- if (matcher.find()) {
|
|
|
- return matcher.group(1);
|
|
|
+ String unquotedSql = sql.replaceAll("\"", ""); // 保留原始大小写,仅移除引号
|
|
|
+ final String TABLE_NAME_REGEX = "([\\w\\u4e00-\\u9fa5.]+)"; // 包含中文、字母、数字、下划线和点的正则
|
|
|
+
|
|
|
+ Pattern[] patterns = {
|
|
|
+ // SELECT 语句 (添加 AS 和 WHERE 的排除)
|
|
|
+ Pattern.compile("(?i)\\bFROM\\s+" + TABLE_NAME_REGEX + "(?=\\s|$|(?:\\s+(?:WHERE|GROUP|HAVING|ORDER)))"),
|
|
|
+ // INSERT 语句
|
|
|
+ Pattern.compile("(?i)\\bINTO\\s+" + TABLE_NAME_REGEX + "\\b"),
|
|
|
+ // UPDATE 语句
|
|
|
+ Pattern.compile("(?i)\\bUPDATE\\s+" + TABLE_NAME_REGEX + "\\b"),
|
|
|
+ // DELETE 语句
|
|
|
+ Pattern.compile("(?i)\\bDELETE\\s+FROM\\s+" + TABLE_NAME_REGEX + "\\b"),
|
|
|
+ // CREATE TABLE 语句 (排除 IF NOT EXISTS)
|
|
|
+ Pattern.compile("(?i)\\bCREATE\\s+TABLE(?:\\s+IF\\s+NOT\\s+EXISTS)?\\s+" + TABLE_NAME_REGEX + "\\b"),
|
|
|
+ // DROP TABLE 语句
|
|
|
+ Pattern.compile("(?i)\\bDROP\\s+TABLE(?:\\s+IF\\s+EXISTS)?\\s+" + TABLE_NAME_REGEX + "\\b")
|
|
|
+ };
|
|
|
+
|
|
|
+ for (Pattern pattern : patterns) {
|
|
|
+ Matcher matcher = pattern.matcher(unquotedSql);
|
|
|
+ if (matcher.find()) {
|
|
|
+ return matcher.group(1);
|
|
|
+ }
|
|
|
}
|
|
|
return null;
|
|
|
}
|