Home > Blockchain >  How to check the syntax of a sql query statement before executing it in python?
How to check the syntax of a sql query statement before executing it in python?

Time:05-10

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related