【发布时间】:2020-10-01 18:27:37
【问题描述】:
我有一张桌子:
CREATE TABLE TABLE_WITH_A_TIMESTAMP
(
TIMESTAMP_ID varchar(4),
TIMESTAMP timestamp
)
还有一个可与其他工具一起使用的 INSERT 命令:
INSERT INTO "my_schema"."table_with_a_timestamp" (timestamp_id, timestamp) VALUES ('0001', {ts '2020-01-01 00:00:00.001'});
现在我想使用 psycopg2 在我的桌子上执行这个命令。
query = """INSERT INTO "my_schema"."table_with_a_timestamp" (timestamp_id, timestamp) VALUES ('0001', {ts '2020-01-01 00:00:00.001'});"""
cursor.execute(query)
这样不行,报错信息是:
syntax error at or near "{"
LINE 1: ...rsion) VALUES ('0001',{ts '2020-...
^
: ProgrammingError
Traceback (most recent call last):
File "/var/task/lambda_function.py", line 35, in lambda_handler
cursor.execute(query)
psycopg2.ProgrammingError: syntax error at or near "{"
LINE 1: ...rsion) VALUES ('0001',{ts '2020-...
有类似的问题将时间戳作为 python 对象处理。但是我不希望解析命令,转换为 python 时间戳,然后进行字符串插值。因为无论如何我都是从文件中读取命令,所以我更愿意以正确的格式(不一定在 python 中)提供命令。 上面的字符串命令的正确格式是什么,以便将时间戳写入表?
我试过了:
"""...,'ts {2020-01-01 00:00:00.001}', ...""" -> 类型时间戳的无效输入语法"""...,"ts {'2020-01-01 00:00:00.001'}", ...""" -> 列“{ts '2001-08-13 10:19:47.701'}”不存在"""...,ts '2020-01-01 00:00:00.001', ...""" -> 类型“ ts" 不存在
【问题讨论】:
标签: python sql postgresql sql-insert psycopg2