Java – replace the table name in the SQL query and the escape characters around the column name

for example

query = " select "2017-06-08" as new_colum,"true" as my_flag,"column1","column2" from "table1" "

The above query should be changed to:

Select "2017-06-08" as new_ Column, select "true" as my in [table1]_ flag,[column1],[column2]. (MS SQL format)

Can I use a parser like jsql parser? Or is there another better way?

Solution

If your date is not enclosed in double quotes, we can use string #replaceall() to complete "(. *?)" with [$1] Complete replacement of But the existence of double quotation marks makes the problem more difficult My updated answers use the following pattern only for non dates in double quotes:

(\s+)"([^\d].*?)"

This will only match a reference term preceded by at least one space character, and the first character in its quotation marks is not a number This should exclude all dates and should not exclude any columns because SQL Server column names cannot start with numbers

I assume here that every referenced column is preceded by a space This should be no problem, assuming that the first word in the query string is always a keyword such as select or update

String query = "select \"2017-06-08\" as new_colum,\"column1\",\"column2\" from \"table1\"";
query = query.replaceAll("(\\s+)\"([^\\d].*?)\"","$1[$2]");
System.out.println(query);

Output:

select "2017-06-08" as new_colum,[column2] from [table1]

By the way, if you want to know the importance of checking spaces before referring to terms, try taking that requirement out of regular expressions You will see that replaceall() will incorrectly start the term with the end quote instead of

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>