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

前端 未结 5 2246
小蘑菇
小蘑菇 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条回答
  • 2021-02-20 07:01

    You could create a temporary table to circumvent side effects of the query:

    CREATE TEMPORARY TABLE users SELECT * FROM users;
    INSERT INTO users(name) VALUES('UniqueName');
    DROP TABLE users;
    SELECT * FROM users WHERE name='UniqueName'; -- Should return 0 results
    
    0 讨论(0)
  • 2021-02-20 07:10

    Not without knowledge of the schema (for example, is 'x' a table?) and writing a SQL parser. Your MySQL query tool should be able to do that kind of validation (intellisense if you like) but I know from first hand experience, most of the (free) MySQL tools are abysmal.

    'Preparing' the query would do what you want, but is a runtime check, not a compile time check - you seem to be looking for a compile time/offline solution.

    0 讨论(0)
  • 2021-02-20 07:13

    You can temporarily create a stored procedure with your code and unique name. Then you can drop it immediately. Transactions can't rollback SP creation. But be careful, because it just syntax validation, so it doesn't check if an object (in your query) exists or not.

    0 讨论(0)
  • 2021-02-20 07:20

    Depending on your MySQL engine and settings, you could start a transaction, try the query, and then do a rollback. Assuming dirty reads are off, that should work.

    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题