Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PreparedStatement - how specify to use default value of column

I have a table created like this:

CREATE TABLE [dbo].[LogInfo](
    [date_current] [datetime] NULL,
    [classname] [varchar](500) NULL,
    [output] [varchar](500) NULL
) ON [PRIMARY]

GO

ALTER TABLE [dbo].[LogInfo] ADD  DEFAULT (getdate()) FOR [date_current]
GO

so the 'date_current' column defaults to the current date and time.

I have a prepared statement like this:

PreparedStatement psInsert_ = conn.prepareStatement("INSERT INTO LogInfo VALUES(?,?,?)");
psInsert_.setTimestamp(1, ????????);
psInsert_.setString(2, "test text1");
psInsert_.setString(3, "test text2");

I'm at a bit of a loss as how to specify the first parameter of the prepared statement and can't find an example of anything like it anywhere.

If I try leave out the default parameter:

PreparedStatement psInsert_ = conn.prepareStatement("INSERT INTO LogInfo ('classname','output') VALUES(?,?)");
psInsert_.setString(1, "test text1");
psInsert_.setString(2, "test text2");

I get an error saying that 'classname' and 'output' are invalid column names.

How should I do this? Thanks.

like image 493
gttommo Avatar asked Oct 18 '25 23:10

gttommo


2 Answers

Don't quote the columns. You can optionally use the DEFAULT keyword:

INSERT INTO LogInfo (date_current, classname, output) VALUES(DEFAULT, ?, ?)
like image 87
Alex K. Avatar answered Oct 20 '25 13:10

Alex K.


The issue in your query is that you use single quotes ' ' which are used for string literals and not object names, you want to use brackets [ ] or nothing at all. Since you have a default defined you can skip that column in the insert statement:

"INSERT INTO LogInfo ([classname],[output]) VALUES(?,?)"

or 

"INSERT INTO LogInfo (classname,output) VALUES(?,?)"

Using delimited identifiers is really only needed when your column name would be invalid for some reason (it might be a reserved keyword, or start with an invalid character, or contain a space etc). Your columns does not need any, so you should/could skip them.

See MSDN: Database Identifiers for more information on the naming rules for SQL Server.

like image 27
jpw Avatar answered Oct 20 '25 12:10

jpw