【问题标题】:Insert PostgreSQL function using Psycopg使用 Psycopg 插入 PostgreSQL 函数
【发布时间】:2023-03-31 10:03:02
【问题描述】:

当argument参数给execute方法时,在使用python变量的情况下:

cur.execute("""
    INSERT INTO some_table (an_int, a_date, a_string)
    VALUES (%s, %s, %s);
    """,
    (10, datetime.datetime.now(datetime.timezone.utc), "O'Reilly"))

所有值都必须是python?是否可以选择传递 PostgreSQL 函数,例如在 UTC 时间的情况下,传递 NOW() 而不是 datetime.datetime.now(datetime.timezone.utc) 或者只能以以下形式完成:

cur.execute("""
        INSERT INTO some_table (an_int, a_date, a_string)
        VALUES (123, NOW(), 'str');
        """)

当所有值都写在 PostgreSQL 中时

【问题讨论】:

  • 不,你可以混合使用。如果这是你的问题。
  • 这很容易测试。你问这个问题的结果是什么?

标签: python postgresql psycopg2


【解决方案1】:

有几种方法可以做到这一点:

cur.execute("""
        INSERT INTO some_table (an_int, a_date, a_string)
        VALUES (%s, NOW(), %s);
        """, [123, 'str'])

cur.execute("""
        INSERT INTO some_table (an_int, a_date, a_string)
        VALUES (%s, %s, %s);
        """, [123, 'now', 'str'])

'now' 有效,因为这是Current Date/time 的特殊情况

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 2014-05-22
    • 1970-01-01
    相关资源
    最近更新 更多