Q:

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.

A:

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.

A:

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;.

