1

As the title says, I want to check the syntax of a query just before executing it in Python. For example, a function named check_syntax:

correct_sql = "select * from table;"
wrong_sql = "selecccct * from table;"

check_syntax(correct_sql) # return True 
check_syntax(wrong_sql)   # return False

I wonder, is there any library in Python that can help? I have looked into sqlparse, but it doesn't help.

2 Answers 2

2

This might be un-ideal but you could do:

def check_syntax(request: str) -> bool:
    try:
        cursor.execute(request)
        return True
    except:
        return False

The problem is that you would not "only check" the syntax. What you could is doing the same but parsing the error message e (except Exception as e) and only returning False if the error code is 102: IncorrectSyntax.

Here is something that could help to parse the exception messages of pyodbc, but depending on what library you use, you'd have to change the class.

Sign up to request clarification or add additional context in comments.

Comments

2

pyparsing includes a SELECT statement parser in its examples directory. You could use it like this:

from pyparsing import Optional, ParseException
from select_parser import select_stmt

def check_syntax(s):
    try:
        (select_stmt + Optional(';')).parseString(s, parseAll=True)
    except ParseException as pe:
        print(pe.explain())
        return False
    else:
        return True

correct_sql = "select * from table;"
wrong_sql = "selecccct * from table;"

print(check_syntax(correct_sql))  # return True
print(check_syntax(wrong_sql))  # return False

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.