Java prepared statement throwing SQLIntegrityConstraintViolationException: Invalid argument(s) in call - java

I am trying to insert a record into DB (Oracle) through Java code. When it is preparing statement at that time it is throwing an exception
java.sql.SQLIntegrityConstraintViolationException: Invalid argument(s) in call
on below line of code:
PreparedStatement ps = connection.prepareStatement(INSERT_QUERY);
and the insert query is:
private static final String INSERT_QUERY = "INSERT INTO ABC ( uid,created_datetime,status,update_datetime,b_id,ref_no,ref_dt,sor,b1_id,c_code,base,name,src,trn_date,country,pr,cv,features,scoring_time_ms,scoring_request_time_ms,preprocessing_time_ms,postprocessing_time_ms,overall_time_ms )VALUES ( ?,current_timestamp,?,current_timestamp,?,?,?,?,?,?,?,?,?,current_timestamp,?,?,?,?,?,?,?,?,? )";
When I debugged the code I found that when it is preparing statement connection.prepareStatement(INSERT_QUERY); insert query is showing as below:
INSERT INTO ABC ( uid,created_datetime,status,update_datetime,b_id,ref_no,ref_dt,sor,b1_id,c_code,base,name,src,trn_date,country,pr,cv,features,scoring_time_ms,scoring_request_time_ms,preprocessing_time_ms,postprocessing_time_ms,overall_time_ms )VALUES ( ?,systimestamp,?,systimestamp,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,? )
It is changing current_timestamp to systimestamp and also I have 3 current_timestamp in the query and it is missing 3rd one while debugging.
I have deleted all the records from database. DB is empty and it has no constraints, only primary key.
Can anyone help me on this issue. Why is this happening and how can I resolve this?

SQLIntegrityConstraintViolationException points to a db constraint violation. Check the for primary/unique/foreign keys in the table "ABC". Just based on the insert statement, can assume uid must be unique.

This issue is resolved. It was build issue. It was not taking updated code so getting that error. Deleted everything from .m2 dir and build it again and this error got disappeared.

Related

JDBC SqlSyntaxErrorException but statement works in SQL tool

I have a DB2 MERGE INTO statement that gives me a sql syntax exception when I try to execute it from Java, but when I put in the parameters in my SQL tool it runs just fine. I've run this repeatedly both in my SQL tool and in Java, and it always works in the former but fails in the latter. This is the SQL (table and column names have been changed to protect the innocent):
merge INTO sales_table AS target
USING (VALUES ( CAST('2020' AS CHAR(4)), CAST('12' AS CHAR(2)), CAST('AB01' AS CHAR(4)), CAST
(0555.0 AS
DECIMAL(9)), CAST(0.000 AS DECIMAL(9)), CAST('DP079616' AS CHAR(8)) )) AS input_data (
year, month, location, no, orig_no, last_upd_userid )
ON ( target.year = input_data.year
AND target.month = input_data.month
AND target.location = input_data.location )
WHEN matched THEN
UPDATE SET no = input_data.no,
orig_no = input_data.orig_no,
last_upd_userid = input_data.last_upd_userid,
last_upd_tmstmp = CURRENT TIMESTAMP
WHEN NOT matched THEN
INSERT ( year,
month,
location,
no,
orig_no,
creation_userid,
creation_tmstmp,
last_upd_userid,
last_upd_tmstmp )
VALUES ( input_data.year,
input_data.month,
input_data.location,
input_data.no,
input_data.orig_no,
input_data.last_upd_userid,
CURRENT TIMESTAMP,
input_data.last_upd_userid,
CURRENT TIMESTAMP )
In the query above I have replaces the ?s with hard-coded parameters that Java sets with the set... methods.
I get this exception in Java:
com.ibm.db2.jcc.am.SqlSyntaxErrorException: DB2 SQL Error: SQLCODE=-270, SQLSTATE=42997, SQLERRMC=null, DRIVER=4.21.29
This is the relevant Java part:
req.setString(i++, roaa.getYear());
req.setString(i++, roaa.getMonth());
req.setString(i++, roaa.getLocatoin());
req.setFloat(i++, Float.parseFloat(roaa.getSalesNumber()));
req.setFloat(i++, Float.parseFloat(roaa.getOrigSalesNumber()));
req.setString(i++, userId);
req.executeUpdate();
Any thoughts on why I'd get a syntax exception on something that works in my SQL tool? Obviously the syntax is right if it works. I've Googled the SQL code -270, and various results say it's because it violates a constraint somewhere, but again, it works in the SQL tool, so I can't help thinking I'm overlooking something simple that should be obvious to me.

JOOQ store() does not return ResultSet

Following this I try to create a new Student Record, assign it some Values and store it to the Database.
DSLContext ctx = ...
StudentRecord s = ctx.newRecord(Student.STUDENT);
s.setFirstname("Nicolas");
s.setLastname("Nox");
s.setGender("M");
s.setYearOfBirth((short) 1990);
s.store(); <-- ERROR
EDIT 1:
The same goes for insert()
End of Edit 1
EDIT 2:
The Student Table contains nothing more than the four values shown above. The Model is autogenerated and select worked so far.
End of Edit 2
Edit 3:
As asked here the Table Definition for Student and the dependency of the JDBC Driver.
create table [LECTURE_DB].[dbo].[STUDENT](
[ID] int identity(1, 1) not null,
[FIRSTNAME] nvarchar(20) not null,
[LASTNAME] nvarchar(20) not null,
[YEAR_OF_BIRTH] smallint null,
[GENDER] nvarchar(1) null,
constraint [PK__STUDENT__3214EC277F60ED59]
primary key ([ID]),
constraint [STUDENT_NAME_IDX]
unique (
[LASTNAME],
[FIRSTNAME]
)
)
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>mssql-jdbc</artifactId>
<version>7.0.0.jre8</version>
</dependency>
End of Edit 3
This does insert a Value into the Database but the Record is not correctly updated.
The following Error is thrown:
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: org.jooq.exception.DataAccessException: SQL [declare #result table ([ID] int); insert
into [LECTURE_DB].[dbo].[STUDENT] ([FIRSTNAME], [LASTNAME], [YEAR_OF_BIRTH], [GENDER]) output
[inserted].[ID] into #result values (?, ?, ?, ?); select [r].[ID] from #result [r];]; The statement did not return a result set.
at org.jooq_3.12.1.SQLSERVER2014.debug(Unknown Source)
at org.jooq.impl.Tools.translate(Tools.java:2717)
at org.jooq.impl.DefaultExecuteContext.sqlException(DefaultExecuteContext.java:755)
at org.jooq.impl.AbstractQuery.execute(AbstractQuery.java:383)
at org.jooq.impl.TableRecordImpl.storeInsert0(TableRecordImpl.java:206)
at org.jooq.impl.TableRecordImpl$1.operate(TableRecordImpl.java:177)
at org.jooq.impl.RecordDelegate.operate(RecordDelegate.java:130)
at org.jooq.impl.TableRecordImpl.storeInsert(TableRecordImpl.java:173)
at org.jooq.impl.UpdatableRecordImpl.store0(UpdatableRecordImpl.java:196)
at org.jooq.impl.UpdatableRecordImpl$1.operate(UpdatableRecordImpl.java:136)
at org.jooq.impl.RecordDelegate.operate(RecordDelegate.java:130)
at org.jooq.impl.UpdatableRecordImpl.store(UpdatableRecordImpl.java:132)
at org.jooq.impl.UpdatableRecordImpl.store(UpdatableRecordImpl.java:124)
at de.esteam.lecturedb.jooq.LectureDBSetup.insertInitialData(LectureDBSetup.java:49)
at de.esteam.lecturedb.jooq.LectureDBAnalysis.<init>(LectureDBAnalysis.java:77)
at de.esteam.lecturedb.jooq.LectureDBAnalysis.<clinit>(LectureDBAnalysis.java:44)
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set. at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(SQLServerException.java:206)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:464)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:405)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:7535)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:2438)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:208)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:183)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(SQLServerPreparedStatement.java:317)
at org.jooq.tools.jdbc.DefaultPreparedStatement.executeQuery(DefaultPreparedStatement.java:94)
at org.jooq.impl.AbstractDMLQuery.executeReturningQuery(AbstractDMLQuery.java:1137)
at org.jooq.impl.AbstractDMLQuery.execute(AbstractDMLQuery.java:935)
at org.jooq.impl.AbstractQuery.execute(AbstractQuery.java:369)
... 12 more
stating the missing ResultSet from the Database to update the ID in my Application.
I kinda need the Records and the IDs since I need to insert many values with foreign keys.
jOOQ using SQL Server OUTPUT to fetch result data from DML statements is a new feature from jOOQ 3.12: #4498. It has a few known issues in version 3.12.2, including:
https://github.com/jOOQ/jOOQ/issues/8917
Yours was not known yet. I'll update my answer once I know more about it.
A workaround could be to turn off generating the OUTPUT clause in SQL Server, which should still work for single-row DML statements like yours. Set your Settings.renderOutputForSQLServerReturningClause flag to false

If insert statement gives duplicate key exception(row id=1 found in table) how to update the statement in JDBC(Postgresql)

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

Delete column from database

I have a database with so many values.How can i delete a specified row using a query.
I am using following query for deletion.I want to delete a row whith the help of colum name=user_name.(user_name=example).
But example named row is not present at the table.is shows error.Any if exist query for this
preparedStatement = (PreparedStatement) connection.prepareStatement("DELETE FROM users WHERE IF EXISTS user_name=example");
preparedStatement.executeUpdate();
The following error occur when i trying to compile
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 'EXISTS user_name='example'' at line 1
remove IF EXISTS
use user_name='example' (with quotes) or even better user_name=? with PreparedStatement
use preparedStatement.executeUpdate()
it shouldnt throw any error even if no result
I think you just forgot the apostrophs that span the String literal 'example':
DELETE FROM users WHERE user_name='example'.
The 'WHERE EXISTS' is unnecessary here!
Greetings
Christopher
I tried here in my computer this way and works fine
PreparedStatement pt =con.prepareStatement("DELETE FROM users WHERE IF EXISTS user_name='"+"example'");
pt.executeUpdate();
I made a temporary table and run it

New to mysql, query throwing wrong syntax

I am trying to pass this query from my Java application but it is saying I have an error in the UPDATE line, but i cant find what is wrong? can you spot see what I am doing wrong?
int rs = st.executeUpdate("INSERT INTO timesheet (employeeID, statusCode, periodEndingDate, departmentCode, minutesMon,"+
"minutesTue, minutesWed, minutesThu, minutesFri, minutesSat, minutesSun)"+
" VALUES ('"+empID+"','"+statusCode+"','"+periodEndingDate+"','"+departmentCode+"','"+minutesMon+"','"+
minutesTue+"','"+minutesWed+"','"+minutesThu+"','"+minutesFri+"','"+minutesSat+"','"+minutesSun+"')"+
" ON DUPLICATE KEY UPDATE timesheet SET statusCode='"+statusCode+"', periodEndingDate='"+periodEndingDate+"', departmentCode='"+departmentCode+"',"+
" minutesMon = '"+minutesMon+"', minutesTue='"+minutesTue+"', minutesWed='"+minutesWed+"', minutesThu='"+minutesThu+"', minutesFri='"+minutesFri+"',"+
" minutesSat='"+minutesSat+"', minutesSun='"+minutesSun+"' WHERE periodEndingDate='"+periodEndingDate+"' AND employeeID='"+empID+"';");
You can't use a WHERE clause with ON DUPLICATE KEY UPDATE. It is updating the duplicate.
If you have a UNIQUE index on (periodEndingDate, employeeID), it is already updating the correct row without the where clause. Also, lose the tablename and the SET in the Update clause.
MySQL Docs on ON DUPLICATE KEY UPDATE

Categories