如果它不存在使用Derby Db如何创建表 [英] how to create table if it doesnt exist using Derby Db
问题描述
我是新来的 apache derby
,我似乎无法工作
I am new to apache derby
and I cant seem to make work
CREATE TABLE IF NOT EXISTS table1 ...
c> MySql 等我得到一个'语法错误:在第1行,第17列遇到NOT'
,当我尝试请在我的 Java
程序中运行此 SQL
语句。
as can be achieved in MySql
etc. I am getting a 'Syntax error: Encountered "NOT" at line 1, column 17.'
, when I try to run this SQL
statement in my Java
program.
我在文档页面中查看了 Derby Db创建语句,但couldn找不到这样的替代方案。
I checked in the documentation page for Derby Db Create Statements, but couldn't find such an alternative.
推荐答案
创建表,捕获 SQLException
并检查SQL状态代码。
Create the table, catch the SQLException
and check SQL status code.
可以找到完整的错误代码列表这里 但我找不到您需要的代码是 Table< value>已存在
;它可能是 X0Y68
。 X0Y32
。
The full list of error codes can be found here but I couldn't find The code you need is Table <value> already exists
; it's probably X0Y68
.X0Y32
.
只需运行一次代码并打印错误代码。不要忘记添加一个测试来确保代码工作;这样,你可以捕获错误代码中的更改(不应该发生...)。
Just run the code once and print the error code. Don't forget to add a test to make sure the code works; this way, you can catch changes in the error code (should not happen ...).
在我的项目中,我通常添加一个辅助类,可写:
In my projects, I usually add a helper class with static methods so I can write:
} catch( SQLException e ) {
if( DerbyHelper.tableAlreadyExists( e ) ) {
return; // That's OK
}
throw e;
}
另一个选择是运行 SELECT
并检查状态代码(应为 42X05
)。但是这是您需要发送的第二个命令,它不提供任何其他信息。
Another option is to run a SELECT
against the table and check the status code (which should be 42X05
). But that's a second command you need to send and it doesn't offer any additional information.
更糟糕的是,它可能会失败,因为表不存在,所以创建和忽略错误是更好的IMO。
What's worse, it can fail for other reasons than "Table doesn't exist", so the "create-and-ignore-error" is better IMO.
这篇关于如果它不存在使用Derby Db如何创建表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!