Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Is there a way to setXXX a column to DEFAULT in a PreparedStatement?

 
Yuriy Zilbergleyt
Ranch Hand
Posts: 429
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

I know that the SQL Query "INSERT INTO (col1, col2) ('someValue', DEFAULT)" will make sure that the value in col2 of the new record be whatever the default value for that column is. Is there a way to do this with a PreparedStatement?

I'm looking to use the following query with a PreparedStatement:
"INSERT INTO (col1, col2) (?, ?)"

However, there is no PreparedStatement.setDefault(int). Hardcoding DEFAULT into the query, or only inserting the non-default columns would defeat the whole point of using PreparedStatements.

Thank you,
Yuriy Zilbergleyt
 
Dave Salter
Ranch Hand
Posts: 293
Java Mac OS X Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you want to use a default value, don't specify the field in the SQL query - the database should then use its default value.
 
Yuriy Zilbergleyt
Ranch Hand
Posts: 429
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply Dave!

Unfortunately that defeats the point of using a PreparedStatement in preference of a plain old Statement. I would like to have a single prepared statement for this type of query, and execute it multiple times in a loop, setting different values from different columns. During some iterations, I will need to insert using the column's default values, which the java code doesn't know. If I don't set one of the (?)s using setXXX, I get an exception. There are actually something like 18 different columns in the table that can be default, so I can't just use two different PreparedStatements.

Thanks,
Yuriy
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 65221
95
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
PreparedStatement.setNull()
 
Yuriy Zilbergleyt
Ranch Hand
Posts: 429
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I tried that, Bear, but MySql at least tries to actually set the columns to NULL, instead of their default values, throwing a SQLException because the columns have the NOT NULL attribute.

Thanks,
Yuriy
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic