将日期时间传递给 psycopg2

Passing a datetime into psycopg2

我正在尝试使用 Psycopg2 将日期时间值插入到我的 postgres 数据库中。

我的代码之前可以正常工作,但我从 %s 表示法切换到 {} 表示法,然后我的代码出错了。

这是我的代码

for j in eveLists.itemList:
    tempPrice = fetchSellPrice(i, j)
    database_name = eveLists.DatabaseDict[i]
    now = datetime.datetime.utcnow()

    cur.execute("INSERT INTO {0} VALUES ({1}, {2}, {3}, NULL, {4}, {5}, NULL);".format(
                                                                                       database_name,
                                                                                       str(i),
                                                                                       str(j),
                                                                                       float(tempPrice),
                                                                                       datetime.date.today(),
                                                                                       now))

我收到以下错误:

psycopg2.ProgrammingError: syntax error at or near "00"
LINE 1: ...0000142, 2268, 3.11, NULL, 2017-05-09, 2017-05-10 00:40:03.3...
                                                             ^

它将日期和时间视为两个单独的对象。

我尝试了几种被注释掉的不同方式,并且都抛出各种错误消息。我试过将日期时间用引号引起来,

now = ("'%s'") % str(datetime.datetime.utcnow())

会报错

psycopg2.ProgrammingError: column "mydate" is of type date but expression is of type integer
LINE 1: ...NTO temp_jita VALUES (30000142, 2268, 3.11, NULL, 2017-05-09...
                                                             ^
HINT:  You will need to rewrite or cast the expression.

它认为我的日期是一个整数,即使我用引号引起来了。

我也试过手动制作 psycopg2 时间戳:

now = psycopg2.Timestamp(now.strftime("%Y"),
                                     now.strftime("%m"),
                                     now.strftime("%d"),
                                     now.strftime("%h"),
                                     now.strftime("%M"),
                                     int(now.strftime("%-S")))

这给出了以下错误:

    int(now.strftime("%-S")))
TypeError: an integer is required (got type str)

我不知道它怎么认为这是一个字符串,特别是因为我将它转换为一个 int!

如有任何帮助,我们将不胜感激。

编辑:我使用 {} 符号而不是 %s 符号传递变量的原因是因为我收到以下代码的错误:

  for j in eveLists.itemList:
            tempPrice = fetchSellPrice(i, j)
            database_name = eveLists.DatabaseDict[i]
            now = datetime.datetime.utcnow()
            now = str(now)

            cur.execute("INSERT INTO %s VALUES (%s, %s, %s, NULL, %s, %s, NULL);", [database_name,
                                                                                    str(i),
                                                                                    str(j),
                                                                                    float(tempPrice),
                                                                                    datetime.date.today(),
                                                                                    now
                                                                                    ])

psycopg2.ProgrammingError: syntax error at or near "'temp_jita'"
LINE 1: INSERT INTO 'temp_jita' VALUES ('30000142', '2268', 3.03, NU...
                    ^

请参考我之前关于这个问题的post:

编辑:按照@Zorg 的建议link (http://initd.org/psycopg/docs/sql.html),这段代码对我有用:

cur.execute(sql.SQL("INSERT INTO {} VALUES (%s, %s, %s, NULL, %s, %s, NULL);").format(sql.Identifier(database_name)),[
                                                                                    str(i),
                                                                                    str(j),
                                                                                    float(tempPrice),
                                                                                    datetime.date.today(),
                                                                                    now
                                                                                    ])

你读过"Psycopg2 usage"了吗?

如果没有,请不要犹豫。

Warning NEVER, NEVER, NEVER use Python string concatenation (+) or string parameters interpolation (%) to pass variables to a SQL query string. Not even at gunpoint.

将参数传递给查询的正确方法如下所示:

 SQL = "INSERT INTO authors (name) VALUES (%s);" # Note: no quotes
 data = ("O'Reilly", )
 cur.execute(SQL, data) # Note: no % operator

AsIs andquote_ident

from psycopg2.extensions import AsIs, quote_ident

cur.execute("""
    INSERT INTO %s
    VALUES (%s, %s, %s, NULL, %s, %s, NULL);
""", (
    AsIs(quote_ident(database_name, cur)),
    str(i),
    str(j),
    float(tempPrice),
    datetime.date.today(),
    now
))