Inserting nothing into primary auto increment key in Derby database - java

I created table in Derby database that looks something like that:
create table "DATABASE".SOMETABLE (ID INTEGER NOT NULL GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) CONSTRAINT PK PRIMARY KEY,
SOMETHING VARCHAR(50) not null)
Now I would like to be able to insert into that table without specifically listing all the columns I want to insert into. So I would like to do something like this:
insert into sometable values ('','something')
I don't want to insert anything into id column but I don't want to be forced to always list names of all the columns I want to insert into. However if I execute this code I get error for trying to modify auto increment primary key.
In MySQL and many other database systems I could just do this:
insert into sometable values ('','something')
and it would work but Derby gives me an error. I tried putting NULL instead of '' but I just get the same error. Is there any way to not insert anything into the primary key column with auto increment (without specifically listing all the other columns) in Derby database?
Thanks in advance for any answers.

Use:
insert into sometable values (default, 'something')
The default keyword is documented here

Specify the column you're inserting:
insert into sometable (something) values ('something')
(I would recommend specifying columns in general, then the order of the columns in your DDL does not matter)

Related

How to return multiple generated columns after insert in MyBatis(Oracle)

I have table with primary key, which consist of several columns. There is batch insert with special Oracle hook - ignore_row_on_dupkey_index. That hook allow to ignore Unique Constraint Exception, duplicate records just get ignored, whereas non duplicate get successfully inserted. Using simple jdbc I could easily return primary key(consist of several columns) by code:
try(PreparedStatement st = connectio.preparedStatement("insert /* ignore_row_on_dupkey(Table_name, Constraint) */ into TABLE(c1, c2, c3) values(?,?,?)", new String [] {"c1", "c2"})) {
//Batch insert then get generated keys
}
Then I could analyze duplicates by iterating over returned keys.
I want to achieve this the same by MyBatis. I found Options annotation, which allows to do it by setting property useGeneratedKeys and keyColumn. The problem is I have complex primary key, whereas keyColumn has type String.
Also I dont want to use SelectKey annotation.
So my question is can I return several columns value and how by MyBatis or not?
Thank you.
keyColumn allows to specify multiple columns. Here's relevant piece of the documentation (note the last sentence):
keyColumn | (insert and update only) Sets the name of the column in the table with a generated key. This is only required in certain databases (like PostgreSQL) when the key column is not the first column in the table. Can be a comma separated list of columns names if multiple generated columns are expected.
And an example from mybatis tests:
<insert id="insertTable2WithGeneratedKeyXml" useGeneratedKeys="true"
keyProperty="nameId,generatedName" keyColumn="ID,NAME_FRED">
insert into table2 (name) values(#{name})
</insert>

Postgresql, get generated sequence after insert with JDBC

We have a java database abstraction that does a number of inserts for us. At runtime we'll know the table name, the column names to insert and the values. From that we generate a prepared statement and do the insert.
In sql server land we would tack on select id = ##identity to the end of the generated sql to get the newly generated id returned by the query.
Now that we're migrating to postgres this no longer works. It's my understanding that in postgres you can do ,
insert into foo(a, b) values('a', 'b') returning ID
Our problem is that at runtime we don't know the name of the ID column nor do we know the name of the sequence. Is there any way to generically get the value of the newly inserted sequence without knowing the name of the sequence or the name of the column?
If your insert is not triggering further inserts, you can use SELECT LASTVAL(); right after your insert statement

SQLite two rowid's created when I explicitly create one

I have a sqlite table and I need to keep the ids from changing when I VACUUM the database. The documentation says that VACUUM will not change the rowids of a table that has an explicit INTEGER PRIMARY KEY.
So, I created a table with
CREATE TABLE tableName (
"rowid" INTEGER PRIMARY KEY,
"updated" DATETIME DEFAULT (CURRENT_TIMESTAMP),
"description" TEXT
)
But that makes a table with two rowid columns. In SQLite Manager add-on for Firefox I see both, and when I try to access the result set in Java it says "ambiguous column: 'rowid'". Is there a way to explicitly create rowid or do I have to use a different name?
rowid is a column of every SQLite table by default
If a table has a primary key that consists of a single column, and the declared type of that column is INTEGER in any mixture of upper and lower case, then the column becomes an alias for the rowid.
Thus, your rowid column doesn't replace the default rowid. Your key is an alias for the default rowid.
Because of this, you really shouldn't name your column rowid, as it is already used, and will result in "ambiguous column" errors, as you have experienced already.
The documentation is saying that the rowid that SQLite is generating will not be changed if your table contains some INTEGER PRIMARY KEY. The PK does not need to be the rowid.

Create new table entry with new id

The problem
I have a table for some data that has an ID column of type integer (which is also the primary key).
When a new data entry is added to the table, it should get a new ID whereas the ID is not known by the application that inserts the object but it should be given by the database. For example, the IDs should be assigned like 0, 1, 2, ...
Assume that I have all other data for the new entry, how would I do the insert? Normally:
insert into T values(123, 'data');
But now I don't know what to put instead of 123
- would you create some kind of global variable NEXTID in the database that provides the IDs and query/update this value each time before inserting into T?
The questions
How to handle this kind of problem? A solution that is concurrency save is preferable.
How to achieve this with Java/myBatis? I Have a Java class that corresponds to the table structure and a new object should be added to the database, getting a new ID automatically.
Update
What I searched for was auto-increment.
Is there a standard SQL way (database independent) of declaring a column as auto-increment? I am using Apache Derby and GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1) is suggested here.
How does the insert to a table that contains auto-increment columns look like?
What is the best way to get the created auto-increment value after an insert when simultaneaous access to the database is possible?
I'll accept an answer that includes explanation and SQL instructions for declaration and insertion :)
If you are using sqlserver, making column of identity type will solve the purpose something like this
.
ALTER TABLE [dbo].[T] ADD [Column1] INT identity (1, 1)
For others like oracle you can for simple database sequence.
In MySQL you can use
ALTER TABLE table_name ADD id INT AUTO_INCREMENT;
this auto increment the id column, you don't have to give in insert.

order by primary key

I'm trying to do a comparison between the data of a table of a SQLServer database before and after some action.
I'm saving the first data in a file (actually I'm saving the MD5 of the data, but not relevant), so I can compare the new data with it after the action.
The first problem is that the data returned by the query is not always in the same order.
So to solve this problem I thought about using the ORDER BY clause to order the data.
Here comes the second problem. I'm executing a query defined by the user, so the query, and the table may be different.
So here is the question: How can I ORDER BY the PRIMARY_KEY (one or multiple) without previous knowledge of what table will be used??
Any other solution will be also welcomed,
Thanks for your time and effort,
You can use dynamic sql and query the meta tables to discover what the primary key is
SELECT column_name
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
WHERE OBJECTPROPERTY(OBJECT_ID(constraint_name), 'IsPrimaryKey') = 1
AND table_name = 'Person'
With dynamic sql you construct your sql statement like a string and hand it over to sp_executeSQL
More info at http://msdn.microsoft.com/en-us/library/ms188001.aspx
I'm trying to do a comparison between the data of a table of a
SQLServer database before and after some action.
If you are using SQL Server 2008, you can use CDC
Do you really need to order by the primary key? If not you can do
ORDER BY 1, 2, 3
that will order by column 1, 2 and 3 regardless the name of the column.
That would work on the PK if you have your Primary key on the first column of the table

Categories