Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

JDBC and Autonumbers

 
Rik Abel
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello everyone,
The problem i'm having is a small one i hope.
I want to add an object to the database.
The database needs a primary key the object doesn't.
Too me this sounds like an autonumber in the db would be good, but i can't
program a suitable preparedstatement because the code i send is a column out eg.
PreparedStatement addDiary = connection.prepareStatement(
"INSERT INTO diary( name,date,time)
"VALUES ( ?, ?, ? )" ) ;
addDiary.setString( 1, z.getName());
addDiary.setString( 2, z.getDate());
addDiary.setString( 3, z.getTime());
addDiary.executeUpdate();
Send 3 attributes, but the db has 4: diarykey, name, date, time.
Any ideas?
 
Wayne L Johnson
Ranch Hand
Posts: 399
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There are various ways in which keys can be generated, and you just have to make sure your INSERT statement is in harmony with the database. Four common policies are:
1) Database auto-number (created on INSERT)
2) Database sequence (Oracle supports this)
3) Defined in Table/Column (select, increment, update)
4) Application generated
In the first case your PreparedStatement can have only three columns, as in your code example. However in the other three cases you must specify all four columns and four associated values in the PreparedStatement.
What database are you running, and how is the "DiaryKey" column defined?
 
Rik Abel
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply.
The first way you mention with the INSERT is how I have finally managed to get the thing working with one of the tables.
However, when I add an autonumber primary key to another table and then
INSERT, it throws a INSERT error - a big inconsistency.
I'm using MS Access.
Do you think I must use Prepared Statements?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic