Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java中如何区分PrimaryKey和uniquekey约束_Java_Sql_Oracle - Fatal编程技术网

java中如何区分PrimaryKey和uniquekey约束

java中如何区分PrimaryKey和uniquekey约束,java,sql,oracle,Java,Sql,Oracle,在PrimaryKey冲突和uniqueKey冲突两种情况下,我看到相同的消息、错误代码和sql状态值 当我直接在db中运行insert查询时,两种情况下都会得到相同的错误消息。唯一的区别是约束名称。我们不能一直依赖约束名称。如何区分不同类型的SQL约束冲突 try { // create Db connection & sql insert into table statement // stmt.executeUpdate("insert into myta

在PrimaryKey冲突和uniqueKey冲突两种情况下,我看到相同的消息、错误代码和sql状态值

当我直接在db中运行insert查询时,两种情况下都会得到相同的错误消息。唯一的区别是约束名称。我们不能一直依赖约束名称。如何区分不同类型的SQL约束冲突

try {

      // create Db connection & sql insert into table statement
      // stmt.executeUpdate("insert into mytable  (A,B) .......")
      // mytable has primary key on column A and unique key on column B

}catch(Exception e){
      System.out.println(">>>>>>>>>> get Message :: " + e.getMessage());
      System.out.println(">>>>>>>>>> get err code:: " + ((SQLException)e).getErrorCode());
      System.out.println(">>>>>>>>>> get sql state:: " + ((SQLException)e).getSQLState());      
}  
测试1:

>>>>>>>>>> get Message :: ORA-00001: unique constraint (TABLE_NAME.UK) violated
>>>>>>>>>> get err code:: 1
>>>>>>>>>> get sql state:: 23000

测试2:

>>>>>>>>>> get Message :: ORA-00001: unique constraint (TABLE_NAME.PK) violated
>>>>>>>>>> get err code:: 1
>>>>>>>>>> get sql state:: 23000
我们不能一直依赖约束名称

为什么
约束名称必须是唯一的。
因此,为了以编程方式区分SQLException和约束冲突,以及约束冲突和另一个约束冲突,两者都是相同的约束类型,因此具有相同的错误代码,您可以检查约束名称。

如果不想使用这种方式,则必须手动检查要插入的数据是否违反表上设置的约束。

这也是一种继续进行的方式,但在插入之前系统地执行检查会更加昂贵。

给定名称(
PK
UK
),您能找到关于该名称的元数据吗

例如,Oracle有
ALL_约束
ALL_索引
表<代码>所有约束有一个
约束类型
列,其中P=主键<代码>所有索引都有一个
唯一性
列,其值为UNIQUE或ununique


希望您的数据库有类似的功能。

如果您知道约束名称和模式所有者,您可以从all_constraints表中查找约束类型

例如:

select constraint_type from all constraints where owner='<your schema owner>'
and constraint_name = '<constraint name returned in your error>'
从所有者为“”的所有约束中选择约束类型
和约束_name=''

在这里查找各种约束类型代码-

您查找过吗?@randomInstanceFlivingThing我了解UK和PK之间的区别。当错误发生时,我需要识别这些错误并进行相应的处理。为什么要区分这些情况?违反了唯一约束的信息还不够吗?