How to check if MySQL query is valid without executing it?

前端 未结 5 2348
小蘑菇
小蘑菇 2021-02-20 06:24

I\'m making a simple tool that will get a string of MySQL commands and run it (on several DB servers sequentially). I trust the users to be sensible, but mistakes happen, and I\

5条回答
  •  梦毁少年i
    2021-02-20 07:23

    To verify a query i use the EXPLAIN command. You can take any SQL query and add EXPLAIN before it and execute. If query is wrong, error will be returned.

    Examples:

    explain select * from users;
    +----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------+
    | id | select_type | table | partitions | type | possible_keys | key  | key_len | ref  | rows | filtered | Extra |
    +----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------+
    |  1 | SIMPLE      | users | NULL       | ALL  | NULL          | NULL | NULL    | NULL |    1 |   100.00 | NULL  |
    +----+-------------+-------+------------+------+---------------+------+---------+------+------+----------+-------+
    

    And wrong query

    explain select * from users2;
    ERROR 1146 (42S02): Table 'test.users2' doesn't exist
    

    P.S. Explain works for insert, update, delete too. Not only select

提交回复
热议问题