5

I am trying to insert NOW into a MySQL table. Something like:

<cfset datatime = CREATEODBCDATETIME( Now() ) />

<cfquery name="qInsert" datasource="#dbanme#" >
   INSERT INTO TableName(....,date_created, date_modified)
   VALUES(...,'#datatime#', '#datatime#')
</cfquery>

But I am getting the following error:

Invalid JDBC timestamp escape

Any help?

4

4 回答 4

12

Let ColdFusion write out the data for you - using cfqueryparam. It's not absolutely essential here, but it's good practice to use it whenever you can. In addition to protecting you from SQL injection, it formats your variables appropriately so you don't have to worry about whether or not you need to insert the values as strings or integers or whatever.

<cfset datatime = CREATEODBCDATETIME( Now() ) />

<cfquery name="qInsert" datasource="#dbanme#" >
   INSERT INTO TableName(....,date_created, date_modified)
   VALUES(...,
        <cfqueryparam value="#datatime#" cfsqltype="cf_sql_timestamp">,
        <cfqueryparam value="#datatime#" cfsqltype="cf_sql_timestamp">
    )
</cfquery>
于 2013-03-05T16:39:41.193 回答
7

如果您想要日期而不是时间,请使用以下命令:

<cfquery name="qInsert" datasource="#dbanme#" >
   INSERT INTO TableName( ...., date_created, date_modified )
   VALUES ( ...
        , <cfqueryparam cfsqltype="cf_sql_date" value="#now()#">
        , <cfqueryparam cfsqltype="cf_sql_date" value="#now()#">
   )
</cfquery>

cf_sql_date将删除任何时间,并根据您的字段类型仅显示日期或日期00:00:00作为时间值。

如果你想要一个有时间的日期:

<cfquery name="qInsert" datasource="#dbanme#" >
   INSERT INTO TableName ( ....,date_created, date_modified )
   VALUES ( ...
      , <cfqueryparam cfsqltype="cf_sql_timestamp" value="#now()#">
      , <cfqueryparam cfsqltype="cf_sql_timestamp" value="#now()#">
   )
</cfquery>
于 2013-03-05T16:48:21.657 回答
4

如果您想使用内置的 NOW 函数,只需将其作为查询的一部分包括在内:

<cfquery name="qInsert" datasource="#dbname#" >
   INSERT INTO TableName(....,date_created, date_modified)
   VALUES(...,NOW(), NOW())
</cfquery>
于 2013-03-05T16:44:11.393 回答
0

插入 SQL Server 时,您不需要在生成的 ColdFusion 时间戳周围加上引号。

详细地说,如果您使用 DateFormat 等将时间戳构建为字符串,则必须使用以下格式插入:

INSERT INTO TABLE(DATE_COL) VALUES({ts '#dateInAStringFormat#'})

日期的 ColdFusion ODBCx 函数为您完成所有这些工作,所以它只是:

INSERT INTO TABLE(DATE_COL) VALUES( #dateInAStringFormat# )
于 2013-03-05T16:35:12.320 回答