Previously i had some experience with MS Access and now i am doing JDBC, in Java of course. In MS Access Databases i can have a AutoNumber field, which is very convenient for generating primary keys. I would like to do the same in Java. However, after digging in SO(and google of course) for a few days, what i can find is just some very handy way. One of them is to firstly get the largest primary key( say N ) in the table, and then you insert the latest record with a key of (N+1). This works, i guess, but not efficient. Can any SO genius help me?
Asked
Active
Viewed 1,274 times
0
-
I think, if you fire your insert query through JDBC without specifying primary key (which is set AutoNumber in database), it should insert new record with automatically generated key. – JProgrammer Feb 28 '12 at 17:44
-
I believe you want to insert records, and then getting the generated keys, if that's your case, I think you shall ignore the batching mode. – Amir Pashazadeh Feb 28 '12 at 18:06
-
no wonder nobody answers a couple of similar questions, i'm an idiot missing this. Thank you! – n0obiscuitz Feb 29 '12 at 15:15
3 Answers
1
MySQL has a similar capability: auto increment. Just add this to your key fields and you're done.

duffymo
- 305,152
- 44
- 369
- 561
1
Not sure which bit you are stuck on
but in MySql Auto number is basically.
CREATE TABLE table_name
(
id INTEGER AUTO_INCREMENT PRIMARY KEY ,
Value INTEGER
)
To use it from something like Java, just skip it in the sql e.g.
Insert table_name(Value) Values(10)

Tony Hopkinson
- 20,172
- 3
- 31
- 39
1
This is not really related to JDBC
.
You have to create the table in mysql
with an auto-incrementing column (Take a look at INTEGER AUTO_INCREMENT PRIMARY KEY
for the column specifications).
Then in JDBC
you just ignore that column when you insert data (like it didn't exist) and the database will take care of it!

Marsellus Wallace
- 17,991
- 25
- 90
- 154