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?
- 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– JProgrammer2012-02-28 17:44:30 +00:00Commented Feb 28, 2012 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– Amir Pashazadeh2012-02-28 18:06:13 +00:00Commented Feb 28, 2012 at 18:06
- no wonder nobody answers a couple of similar questions, i'm an idiot missing this. Thank you!n0obiscuitz– n0obiscuitz2012-02-29 15:15:32 +00:00Commented Feb 29, 2012 at 15:15
Add a comment |
3 Answers
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!