【问题标题】:python: psql: insert into table on conditionspython:psql:根据条件插入表
【发布时间】:2015-10-09 09:14:14
【问题描述】:

我有一个 psql 表“inlezen”,其中包含“tagnaam”和“melding”列。 现在,如果“tagnaam”等于变量“foutetag”,我想在“meldingen”列中插入一个字符串。

我尝试了一些查询,语法混乱但无法正常工作。 这是我的代码:

cur.execute("INSERT INTO inlezen (melding) WHERE tagnaam == foutetag VALUES (%s)", ("Fout bij schrijven naar OPC Server",)) 
conn.commit() 

但它给出了错误:

Traceback (most recent call last):
  File "OPCSchrijvenLezen.py", line 71, in <module>
    cur.execute("INSERT INTO inlezen (melding) WHERE tagnaam == foutetag VALUES (%s)", ("Fout bij schrijven naar OPC Server",)) 
psycopg2.ProgrammingError: syntax error at or near "WHERE"
LINE 1: INSERT INTO inlezen (melding) WHERE tagnaam == foutetag VALU...

有人知道这段代码有什么问题吗?

提前致谢!

在 Mathias Ettinger 回答后编辑:

我改了代码,报错也变了一点:

Traceback (most recent call last):
  File "OPCSchrijvenLezen.py", line 72, in <module>
    cur.execute("INSERT INTO inlezen (melding) WHERE tagnaam = %s VALUES (%s)", (foutetag, "Fout bij schrijven naar OPC Server",))
psycopg2.ProgrammingError: syntax error at or near "WHERE"
LINE 1: INSERT INTO inlezen (melding) WHERE tagnaam = 'Bakkerij.Devi...
                                      ^

现在它至少“看到”了变量的内容。但是,变量周围有单引号。我不确定他们是否应该在那里。 如果我打印变量“foutetag”,它只会显示:

Bakkerij.Device1.DB100INT8

,就像它在 psql 表中一样。

这就是我生成变量的方式:

foutetag = [item[0] for item in taglistwaardennieuw]
foutetag = (", ".join(foutetag))

我生成变量的方式有什么问题吗?

【问题讨论】:

    标签: python postgresql psycopg2 psql


    【解决方案1】:

    如果foutetag是一个变量,那么你需要这样对待它:

    cur.execute("INSERT INTO inlezen (melding) WHERE tagnaam=%s VALUES (%s)", (foutetag, "Fout bij schrijven naar OPC Server",))
    

    还要注意WHERE 子句中的单个=

    但是INSERT 语句不接受WHERE 子句,因为它将从头开始生成新行。如果您想更新您的值,请使用:

    cur.execute("UPDATE inlezen SET melding=%s WHERE tagnaam=%s", ("Fout bij schrijven naar OPC Server", foutetag))
    

    【讨论】:

    • 我已经在我的 OP 中回复了。
    • 已更新。您的 SQL 语句从一开始就格式不正确
    猜你喜欢
    • 2019-01-28
    • 2015-09-27
    • 1970-01-01
    • 2015-03-28
    • 1970-01-01
    • 2020-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多