简体   繁体   中英

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; 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.

初学者的“ 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

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

select 'bob

To get 1/0 to raise an error in MySQL, you need to set sql_mode to 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.

You can check what your current settings are with the following:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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