Its similar to https://stackoverflow.com/questions/377883/how-to-check-if-mysql-query-is-valid-without-executing-it But its for Go and I want a solution in Python. It will be better if there is a built-in tool with MySQL and related DBMS that checks the syntax of the query.

  • Now, please tell me the reason for downvote... – J Arun Mani Jan 3 '20 at 18:00

If "without executing it" can be interpreted as "without committing it", then you can execute the statement in a try...except...finally clause and roll it back if it does not throw an exception.

Of course, that only ensures that your query is valid SQL, not that it "is right" in the sense of doing what you want it to do. An independent code review is the best way to get that assurance.

  • I agree. How does Mysql do that? Like does it check the query for any error or simply executes it and watches for error? (I will accept your answer, soon, if no better answer is given :) ) – J Arun Mani Jan 3 '20 at 18:00
  • If you execute the query as a transaction in a try...except clause, MySQL will simply try to construct a query plan and execute the query. Those steps may produce an error, indicating that your SQL is incorrect (which may result from a syntax error, a reference to a nonexistent object, a key violation, or possibly other causes). If you don't get an error, the query succeeded and the SQL is valid (though, as noted, not necessarily 'right'). If you didn't really want to run the query, then you need to roll back the transaction. – rd_nielsen Jan 3 '20 at 18:08
  • No not in the connector module. I'm asking in the commandline client, in Terminal, does it also work this way or include any linters? – J Arun Mani Jan 3 '20 at 18:10
  • At the commandline, instead of in Python, you can do the same sort of thing by executing START TRANSACTION;, then your query, and then ROLLBACK; if the query succeeds. In addition, there are linters available; see stackoverflow.com/questions/3970643/… – rd_nielsen Jan 3 '20 at 18:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.