简体   繁体   English

如何编写失败的SQL查询?

[英]How do I write an SQL query that fails?

I need this query for testing exception handling, so I would prefer that the query is not schema dependent. 我需要此查询来测试异常处理,因此我希望查询不依赖于架构。 I am looking for something like SELECT 1; 我正在寻找类似SELECT 1;东西SELECT 1; but of course that doesn't fail. 但是那当然不会失败。

I am using Java and MySQL but I hope to find answers that doesn't depend on programming languages and/or RDBMSs. 我正在使用Java和MySQL,但我希望找到不依赖于编程语言和/或RDBMS的答案。

初学者的“ SELECT 1/0”呢?

You could put an invalid token into the query 您可以在查询中放入无效的令牌

select doesnotexist.* from something_else

Or of course, what you should do is mock out the method and have it throw the exception during your test. 或者,当然,您应该做的是模拟该方法,并在测试期间使其抛出异常。

there are tons of ways to make a query fail, like mispelling a field, or selecting from non existing tables. 有很多方法可以使查询失败,例如拼写错误的字段或从不存在的表中选择。 for example: 例如:

SELECT some_fake_field FROM table_that_doesnt_exists

One way to trigger a failure is to call a stored procedure with the wrong number of parameters. 触发失败的一种方法是使用错误数量的参数调用存储过程。 Another similar idea is to write an update/insert statement with the wrong number of arguments... 另一个类似的想法是用错误数量的参数编写更新/插入语句。

More ideas here: How to raise an error within a MySQL function 更多信息,请参见: 如何在MySQL函数中引发错误

任何旧的语法错误都可以...就像未终止的字符串

select 'bob

To get 1/0 to raise an error in MySQL, you need to set sql_mode to ERROR_FOR_DIVISION_BY_ZERO. 要获得1/0以在MySQL中引发错误,您需要将sql_mode设置为ERROR_FOR_DIVISION_BY_ZERO。

Try this: 尝试这个:

SET sql_mode = 'ERROR_FOR_DIVISION_BY_ZERO';
SELECT 1/0;

If this sql_mode isn't set, MySQL will return a NULL instead of an error. 如果未设置此sql_mode,则MySQL将返回NULL而不是错误。

You can check what your current settings are with the following: 您可以使用以下方法检查当前设置:

SELECT @@GLOBAL.sql_mode;
SELECT @@SESSION.sql_mode;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM