JOOQ store() does not return ResultSet - java
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
Related
H2: Error with a multi-row insert statement
I'm using an in-memory H2 database with an initialisation SQL script. The following table is created: CREATE TABLE GINA_T_WAM_GUESTDOMAIN ( WFD_C_NAME VARCHAR(12) NOT NULL, WFD_C_BASEURI VARCHAR(128) NOT NULL, PRIMARY KEY (WFD_C_NAME, WFD_C_BASEURI), FOREIGN KEY (WFD_C_NAME) REFERENCES GINA_T_WAM_GUEST(WFG_C_NAME) ); Now I can insert some rows in that table like this: INSERT INTO GINA_T_WAM_GUESTDOMAIN(WFD_C_NAME,WFD_C_BASEURI) VALUES('DEVINT', 'https://dev.etat-ge.ch'); INSERT INTO GINA_T_WAM_GUESTDOMAIN(WFD_C_NAME,WFD_C_BASEURI) VALUES('DEVINT', 'https://devtech.etat-ge.ch'); But when I try to insert both rows in a single statement: INSERT INTO GINA_T_WAM_GUESTDOMAIN(WFD_C_NAME,WFD_C_BASEURI) VALUES('DEVINT', 'https://dev.etat-ge.ch'), VALUES('DEVINT', 'https://devtech.etat-ge.ch'); I get the following error message: Column count does not match Does anyone knows about this issue? is it at all possible to insert several lines in one statement?
That's how you can insert multiple rows at the same time in a single SQL statement: VALUES('DEVINT', 'https://dev.etat-ge.ch'), ('DEVINT', 'https://devtech.etat-ge.ch'); It's called row value constructor and is a standard since SQL-92. Source: http://www.andrew.cmu.edu/user/shadow/sql/sql1992.txt (Chapter 7.1)
Java prepared statement throwing SQLIntegrityConstraintViolationException: Invalid argument(s) in call
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.
Unable to fathom update count INSERT on billions of rows
I am running a Netezza SQL query that is creating a table from a select statement returning almost 8 billion rows. Here is the query: CREATE TABLE table1 AS ( SELECT column1 FROM table2 qt WHERE qt.column1 = '2016-04-04' UNION ALL SELECT column1 FROM table3 qt WHERE qt.column1 = '2016-04-04' ) The driver is throwing this error: org.springframework.jdbc.UncategorizedSQLException: SqlMapClient operation; uncategorized SQLException for SQL []; SQL state [UNDEFINED]; error code [0]; --- The error occurred while applying a parameter map. --- Check the statement (update failed). --- Cause: Unable to fathom update count INSERT 0 7779737732 Does anyone know what's causing this?
I think you are running into a JDBC driver limitation. If you run a INSERT, UPDATE, CREATE AS SELECT via JDBC and the number of rows INSERTed, UPDATEd or CREATEd exceeds 2147483647, you will receive an error message similar to the following: Unable to fathom update count INSERT 0 5120000160 The above error message may be different given whether an INSERT, UPDATE or CREATE as SELECT and given the number of rows actually affected. This is a limitation of JDBC specification itself. Thanks, Sanjit
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
How can I get an id for a new record in a generic way? (JOOQ 3.4 with Postgres)
With jooq 3.4 I can't figure out how to do this (with Postgresql): Query query = dsl.insertInto(TABLE) .set(TABLE.ID, Sequences.TABLE_ID_SEQ.nextval()); but in a case when I don't know which is the exact table, something like this: TableImpl<?> tableImpl; Query query = dsl.insertInto(tableImpl) .set(tableImpl.getIdentity(), tableImpl.getIdentity().getSequence().nextval()); Is it somehow possible? I tried this: dsl.insertInto(tableImpl) .set(DSL.field("id"), tableImpl.getSchema().getSequence("table_id_seq").nextval()) This works but I still don't know how to get the sequence name from the TableImpl object. Is there a solution for this? Or is there a problem with my approach? In plain SQL I would do this: insert into table_A (id) VALUES nextval('table_A_id_seq'); insert into table_B (table_A_id, some_val) VALUES (currval('table_A_id_seq'), some_val); So I need the value or a reference to that id for later use of the id that was generated for the inserted record as default, but I don't want to set any other values.
jOOQ currently doesn't have any means of associating a table with its implicitly used sequence for the identity column. The reason for this is that the sequence is generated when the table is created, but it isn't formally connected to that table. Usually, you don't have to explicitly set the serial value of a column in a PostgreSQL database. It is generated automatically on insert. In terms of DDL, this means: CREATE TABLE tablename ( colname SERIAL ); is equivalent to specifying: CREATE SEQUENCE tablename_colname_seq; CREATE TABLE tablename ( colname integer NOT NULL DEFAULT nextval('tablename_colname_seq') ); ALTER SEQUENCE tablename_colname_seq OWNED BY tablename.colname; The above is taken from: http://www.postgresql.org/docs/9.3/static/datatype-numeric.html#DATATYPE-SERIAL In other words, just leave out the ID values from the INSERT statements. "Empty" INSERT statements Note that if you want to create an "empty" INSERT statement, i.e. a statement where you pass no values at all, generating a new column with a generated ID, you can use the DEFAULT VALUES clause. With SQL INSERT INTO tablename DEFAULT VALUES With jOOQ DSL.using(configuration) .insertInto(TABLENAME) .defaultValues() .execute(); Returning IDs Note that PostgreSQL has native support for an INSERT .. RETURNING clause, which is also supported by jOOQ: With SQL INSERT INTO tablename (...) VALUES (...) RETURNING ID With jOOQ DSL.using(configuration) .insertInto(TABLENAME, ...) .values(...) .returning(TABLENAME.ID) .fetchOne();