H2 Java Insert ignore - allow exception

試著忘記壹切 提交于 2019-12-30 18:52:12

问题


I am working on a java plugin interfacing with an H2 database. What I really want is an "Insert Ignore" statement; however, I'm aware that H2 doesn't support this. I am also aware of Merge, but this is really not what I want, if the record exists I don't want to change it.

What I am considering is to just run the insert and let the duplicate key exception happen. However, I don't want this to fill my log file. The DB call happens in an imported class that I can't change. So my questions are:

  1. Is this a reasonable thing to do? I'm not one for letting errors happen, but this seems like the best way in this case (it should not happen all that much).
  2. How can I keep this exception from hitting my log file? If there isn't a way to block exceptions down the stack, can I redirect the output of the stack trace that is output?

Thanks.


回答1:


One solution is to use:

insert into test 
select 1, 'Hello' from dual 
where not exists(select * from test where id = 1)

This should work for all databases (except for the dual part; you may need to create your own dummy table with one row).

To disable logging exceptions, append ;trace_level_file=0 to the database URL:

jdbc:h2:~/test;trace_level_file=0

or run the SQL statement:

set trace_level_file 0


来源:https://stackoverflow.com/questions/6736518/h2-java-insert-ignore-allow-exception

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!