In both cases of PrimaryKey violation and uniqueKey violation, I see the same message, error code and sql state values.
When I run the insert query directly in the db, getting the same error message for both the cases. Only difference is the constraint name. we cannot rely on the constraint name all the time. How to differentiate the different types of SQL constraints violations?
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());
}
Test 1:
>>>>>>>>>> get Message :: ORA-00001: unique constraint (TABLE_NAME.UK) violated
>>>>>>>>>> get err code:: 1
>>>>>>>>>> get sql state:: 23000
Test 2:
>>>>>>>>>> get Message :: ORA-00001: unique constraint (TABLE_NAME.PK) violated
>>>>>>>>>> get err code:: 1
>>>>>>>>>> get sql state:: 23000
we cannot rely on the constraint name all the time
And why ?
The constraint name has to be unique.
Consequently to distinguish programmatically from a SQLException a constraint violation from another one which both are the same constraint type and so have the same error code, you could check the constraint name.
If you don't want to use this way, you have to manually check that the data to insert doesn't violate the constraints set on the table.
It is also a way of proceeding but it will be more expensive to perform systematically a check before inserting.
If you know the constraint name and the schema owner, you can look up the constraint type from the all_constraints table.
For example:
select constraint_type from all constraints where owner='<your schema owner>'
and constraint_name = '<constraint name returned in your error>'
Look here for the various constraint type codes - https://docs.oracle.com/cd/B19306_01/server.102/b14237/statviews_1037.htm#i1576022
Given the name (PK or UK) can you find the meta data about that name?
For example, Oracle has the the ALL_CONSTRAINTS and ALL_INDEXES tables. ALL_CONSTRAINTShas a constraint_type column where P = primary key. ALL_INDEXES has a uniqueness column with values of UNIQUE or NONUNIQUE.
Hopefully your database has something similar.
Related
In hibernate for columns annotated with #Column(unique = true) we get an exception when trying to insert a duplicate value for that column.
2022-07-31 19:47:18.112 ERROR 14372 --- [io-8080-exec-10] o.h.engine.jdbc.spi.SqlExceptionHelper : Duplicate entry ' someValue' for key 'business.UK_3h6o7iww8015m4q3yffbkqtrw'
So from the above log, I know that business is the table in which I am inputting a duplicate value.
Is there a way to know in which column the duplicate value is getting inserted into? Since a single table can have multiple unique columns.
In addition to what Davide D'Alto wrote, you can also enable SQL logging, e. g. as shown here.
You can check the SQL for the table creation:
show create table business;
or you can run the following query:
select COLUMN_NAME
from information_schema.KEY_COLUMN_USAGE
where TABLE_NAME = 'business' and CONSTRAINT_NAME='UK_3h6o7iww8015m4q3yffbkqtrw'
I just managed to connect with a local .accdb Access Database and am now trying to create my tables. I run these two lines with Java and there are no errors during running these SQL-Commands:
Statement st = d.createStatement();
st.executeUpdate("CREATE TABLE suppliers ( [name] TEXT(255), [adress] TEXT(255), [ID] AUTOINCREMENT PRIMARY KEY);");
st.executeUpdate("CREATE TABLE quality ( [name] TEXT(255) );");
st.close();
But now as I want to open the just created tables with Microsoft Access there is a difference between the two generated tables.
I can open the table "quality" normally and insert some values.
Now if I'm trying to open "suppliers" I get this error message:
It is in German and means "The database '' could not been opened. Either the database doesn't get recognized by your application or the file is damaged."
So I tried to remove the "[ID] AUTOINCREMENT PRIMARY KEY" and it works fine without this. So the error must be caused by the "AUTOINCREMENT".
To connect with the database I use ucanacess:
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
c = DriverManager.getConnection("jdbc:ucanaccess://C:/bin/Test.accdb");
Have I done something wrong with my "AUTOINCREMENT"?
I am able to reproduce your issue with UCanAccess 4.0.2. It appears to be related to the [ID] column being specified last. That is, this causes the issue:
sql = "CREATE TABLE suppliers ( [name] TEXT(255), [adress] TEXT(255), [ID] AUTOINCREMENT PRIMARY KEY)";
... but specifying the columns in this order works okay:
sql = "CREATE TABLE suppliers ([ID] AUTOINCREMENT PRIMARY KEY, [name] TEXT(255), [adress] TEXT(255))";
I will pass this information along to the UCanAccess development team.
I have Stored bunch of insert statements in ArrayList.like below
List<String> script=new ArrayList<String>;
script.add("INSERT INTO PUBLIC.EMPLOYEE(ID, NAME) VALUES (1, 'Madhava'));
script.add(INSERT INTO PUBLIC.EMPLOYEE(ID, NAME) VALUES (2, 'Rao'));
script.add(INSERT INTO PUBLIC.ADDRESS(ID, CITY) VALUES(1, 'Bangalore'))
script.add(INSERT INTO PUBLIC.ADDRESS(ID, CITY) VALUES(2, 'Hyd'));
I created connection to the postgresql using jdbc i get executed statments using for loop like below
try{
Connection con=DBConnections.getPostgresConnection();
Statment statment=con.createStatment();
for(String query:script){
executeUpdate(query);
}
}catch(Exception e){
e.printStackTrace();
}
If i get duplication key exception(i.e.Already record exist in postgresDB).
org.postgresql.util.PSQLException: ERROR: duplicate key value
violates unique constraint "reports_uniqueness_index"
How to update the same statment(record) with update query into Postgres.
Is there any way to solve this ?
Is there any other better way to solve this?
Could you please explain...
Execute update sends a DML statement over to the database. Your database must already have a record which uses one of the primary keys either in the employees or address table.
You have to ensure you don't violate the primary key constraint. Violating the constraint is resulting in the exception.
Either change your query to an update statement, or delete the records which are causing conflict.
There is no way to get the key that caused the exception (though you can probably parse the error message, which is certainly not recommended).
Instead, you should try preventing this from ever happenning. There are at least 3 easy ways to accomplish this.
Make the database update the column
(in Postgresql you should use a serial type (which is basically an int data type)
CREATE TABLE employee
(
id serial NOT NULL,
--other columns here )
Your insert will now look like
script.add("INSERT INTO PUBLIC.EMPLOYEE(NAME) VALUES ('Madhava'));//no ID here
Create a sequence and have your JDBC code call the sequence' nexval method.
script.add("INSERT INTO PUBLIC.EMPLOYEE(ID, NAME) VALUES (YOUR_SEQ_NAME.NEXTVAL(), 'Madhava'));
Create a unique ID in Java (least recommended)
script.add("INSERT INTO PUBLIC.EMPLOYEE(ID, NAME) VALUES (UUID.random(), 'Madhava'));//or Math.random() etc
So after creating tables using jdbc, I have this code to make one to many relationship between UserInfoTable and ContactTable and UserInfoID as foreign key.
String addConstraint = "alter table ContactTable"+
"ADD CONSTRAINT FK_ContactTable_UserInfoTable"+
"FOREIGN KEY(UserInfoID)"+
"REFERENCES UserInfoTable (UserInfoID)"+
"ON UPDATE CASCADE"+
"ON DELETE CASCADE";
But when I execute this,
con.prepareStatement(addConstraint).executeUpdate();
I'm getting
java.sql.SQLException: Incorrect syntax near the keyword 'CONSTRAINT'.
I'm really confused. I handcoded this query several times in sql server and I think my syntax is correct because it always executed successfully, why not when executed by java code?
You are concatenating strings but the different segments have no spaces, this could be causing keywords to be bunched together with your data creating invalid keywords.
It is simple but this may be all you need:
String addConstraint = "alter table ContactTable "+
"ADD CONSTRAINT FK_ContactTable_UserInfoTable "+
"FOREIGN KEY(UserInfoID) "+
"REFERENCES UserInfoTable (UserInfoID) "+
"ON UPDATE CASCADE "+
"ON DELETE CASCADE";
I am trying to create 2 tables in MySql using Java JDBC,the first one runs fine but I get an error when I execute the second create table command. The problem looks like in the Foreign key definition not sure what's missing ?
Error :
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have an error in your SQL syntax;
check the manual that corresponds to your MySQL server
version for the right syntax to use near 'FOREIGN KEY(UniqueBusID)
REFERENCES BUS_3_CLEARBROOK_UFV_GOLINE_TO_UFV_BusDetai' at line 1
Code
String table_UniqueBusNameTimings = BusDetails+"_BusTimings";
String timings= "Timings";
String dayofweek = "DayOfWeek";
String FuniqueBusID = "UniqueBusID";
String table_UniqueBusNameDetails = BusDetails+"_BusDetails";
String PuniqueBusID = "UniqueBusID";
String StopNames = "StopNames" ;
String sql1 = "CREATE TABLE "+table_UniqueBusNameDetails+
"(UniqueBusID VARCHAR(255) not NULL, " +
" StopNames VARCHAR(1000), " +
" PRIMARY KEY ( UniqueBusID ))";
String sql2 = "CREATE TABLE "+table_UniqueBusNameTimings+
"(Timings VARCHAR(255) , " +
" DayOfWeek VARCHAR(25), " +
" UniqueBusID VARCHAR(255) "+
" FOREIGN KEY(UniqueBusID) REFERENCES "+table_UniqueBusNameDetails+"(UniqueBusID))";
stmt.executeUpdate(sql1);
stmt.executeUpdate(sql2);
You have a comma missing after UniqueBusID VARCHAR(255). Just change it to UniqueBusID VARCHAR(255), and your code shall be fine.
For details on syntax related to CREATE TABLE with FOREIGN KEY, you can explore this page: http://www.w3schools.com/sql/sql_foreignkey.asp
We should use CREATE TABLE IF NOT EXISTS... then if we are having foreign key relation then we should use SET FOREIGN_KEY_CHECKS=0; Finally we will execute a batch what having all the statement and then commit.
Every attribute like column, index, foreign key etc. should be seprated by comma ',' in table creation syntax. so here a comma missing after UniqueBusID VARCHAR(255). It will be fine after adding comma here.
#Suzon: We should not set foreign_key_checks=0 specially during creating table or adding any constraint at it will skip any constraint checking by mysql and create major issue in database. We can use it only we are sure its impact for example we want to delete some rows from master table even child table contains corresponding rows and we are fine with this etc.