T. Popović
T. Popović

Reputation: 345

Using regular expressions for validating mysql statements

I am writing a program in java. In a dialog a user need to input MySQL SELECT statement. Program must to validate the statement an continue to run. My question is: Is there a way and how to validate the statement with regular expressions. I need "only" regular expression pattern. Thanks.

Upvotes: 5

Views: 2395

Answers (4)

Karol Dowbecki
Karol Dowbecki

Reputation: 44962

If your objective is to allow only SELECT statements than grant only this operation to database user that opens the database connection. After that just handle the SQLException.

You really don't want to write and maintain validation code by hand because there are too many things to remember. For example if your JDBC connection is using allowMultiQueries=true parameter then one can execute multiple statements within String like SELECT * FROM table; DROP TABLE table;.

Upvotes: 3

Daniel Kec
Daniel Kec

Reputation: 549

That's no place for a regex usage.

Elegant way to solve this is using BNF for Java as validator of your select statements. If you will feed it SQL grammar, like this one sql-99.bnf, you will have your statement validator in no time and for free.

Upvotes: 2

Santanu Sahoo
Santanu Sahoo

Reputation: 1157

If it is SELECT statement then it should start with SELECT. Below code is to match anything which starts with SELECT.

String sa = "THIS SELECT * from table;";
System.out.println(sa.matches("(?i)^select .*")); //FALSE as the input string is not valid select statement
sa = "SELECT * from table;";
System.out.println(sa.matches("(?i)^select .*")); //TRUE as the input string is  valid select statement

Upvotes: 2

amit
amit

Reputation: 178461

Well, maybe for extended regex, but for the original meaning of "regex" that stands for "Regular Expression", for "Regular Language" - no.

Each SELECT statement is:

SELECT x FROM y WHERE z

However, since y itself can be a SELECT statement, this is at least as hard as the language of balanced parenthesis, which is irregular.

Upvotes: 4

Related Questions