aspose file tools*
The moose likes JDBC and the fly likes Is there a way to setXXX a column to DEFAULT in a PreparedStatement? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Is there a way to setXXX a column to DEFAULT in a PreparedStatement?" Watch "Is there a way to setXXX a column to DEFAULT in a PreparedStatement?" New topic
Author

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

Yuriy Zilbergleyt
Ranch Hand

Joined: Dec 13, 2004
Posts: 429
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

Joined: Jul 20, 2005
Posts: 293

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

Joined: Dec 13, 2004
Posts: 429
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

Joined: Jan 10, 2002
Posts: 61766
    
  67

PreparedStatement.setNull()


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Yuriy Zilbergleyt
Ranch Hand

Joined: Dec 13, 2004
Posts: 429
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Is there a way to setXXX a column to DEFAULT in a PreparedStatement?