如果使用Derby Db不存在表,如何创建表 [英] how to create table if it doesn't exist using Derby Db

查看:631
本文介绍了如果使用Derby Db不存在表,如何创建表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 apache derby 的新手,我似乎无法工作

I am new to apache derby and I cant seem to make work

    CREATE TABLE IF NOT EXISTS table1 ...

可以用<$ c $实现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创建语句,但是没有找不到这样的替代方案。

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.

可以找到错误代码的完整列表这里 但我找不到表< value>已存在;它可能是 X0Y68 您需要的代码是 X0Y32

The full list of error codes can be found here but I couldn't find Table <value> already exists; it's probably X0Y68. The code you need is 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆