Java PreparedStatement-如何指定使用列的默认值
我创建了一个如下表:Java PreparedStatement-如何指定使用列的默认值,java,sql-server,Java,Sql Server,我创建了一个如下表: 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 Prepare
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
PreparedStatement psInsert_ = conn.prepareStatement("INSERT INTO LogInfo VALUES(?,?,?)");
psInsert_.setTimestamp(1, ????????);
psInsert_.setString(2, "test text1");
psInsert_.setString(3, "test text2");
因此,“date_current”列默认为当前日期和时间
我准备了这样一份声明:
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
PreparedStatement psInsert_ = conn.prepareStatement("INSERT INTO LogInfo VALUES(?,?,?)");
psInsert_.setTimestamp(1, ????????);
psInsert_.setString(2, "test text1");
psInsert_.setString(3, "test text2");
对于如何指定prepared语句的第一个参数,我有点不知所措,但在任何地方都找不到类似的示例
如果我尝试忽略默认参数:
PreparedStatement psInsert_ = conn.prepareStatement("INSERT INTO LogInfo ('classname','output') VALUES(?,?)");
psInsert_.setString(1, "test text1");
psInsert_.setString(2, "test text2");
我得到一个错误,说“classname”和“output”是无效的列名
我该怎么做?谢谢。来自API:
void setDate(int parameterIndex, Date x)
确保您的日期是日期对象
参考:
第二个查询失败,因为列名在单引号中。尝试:
插入LogInfo(类名称,输出)值(?,)不引用列。您可以选择使用
DEFAULT
关键字:
INSERT INTO LogInfo (date_current, classname, output) VALUES(DEFAULT, ?, ?)
我相信您的错误在于,在类名和输出周围有单引号。删除单引号,您的第二种解决方案应该会起作用。查询中的问题是,您使用单引号
'
,用于字符串文本而不是对象名称,您希望使用方括号[]
或什么都不使用。由于已定义默认值,因此可以在insert语句中跳过该列:
"INSERT INTO LogInfo ([classname],[output]) VALUES(?,?)"
or
"INSERT INTO LogInfo (classname,output) VALUES(?,?)"
只有当列名由于某种原因(可能是保留关键字、或以无效字符开头、或包含空格等)无效时,才真正需要使用分隔标识符。您的列不需要,因此您应该/可以跳过它们
有关SQL Server命名规则的更多信息,请参阅MSDN: