0

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?

3
  • 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. Commented 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. Commented Feb 28, 2012 at 18:06
  • no wonder nobody answers a couple of similar questions, i'm an idiot missing this. Thank you! Commented Feb 29, 2012 at 15:15

3 Answers 3

1

MySQL has a similar capability: auto increment. Just add this to your key fields and you're done.

Sign up to request clarification or add additional context in comments.

Comments

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) 

Comments

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!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.