简体   繁体   English

python:psql:根据条件插入表

[英]python: psql: insert into table on conditions

I have a psql table "inlezen" with columns "tagnaam" and "melding". 我有一个psql表“ inlezen”,其中包含“ tagnaam”和“ melding”列。 Now I want to insert a string into column "meldingen" if "tagnaam" equals a variable "foutetag". 现在,如果“ tagnaam”等于变量“ foutetag”,我想在“ meldingen”列中插入一个字符串。

I have tried some queries, messed with the syntax but couldn't get it to work. 我尝试了一些查询,弄乱了语法,但无法正常工作。 This is my code: 这是我的代码:

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

But it gives errors: 但是它给出了错误:

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...

Does anyone know what's wrong with this piece of code? 有人知道这段代码有什么问题吗?

Thanks in advance! 提前致谢!

Edit after Mathias Ettinger's answer: 在Mathias Ettinger的答案之后编辑:

I've changed the code and the error changed a little bit: 我更改了代码,错误有所改变:

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...
                                      ^

Now it "sees" the content of the variable at least. 现在,它至少“看到”了变量的内容。 However, there are single quotation marks around the variable. 但是,变量周围有单引号。 I'm not sure if they should be there. 我不确定他们是否应该在那里。 If I print the variable "foutetag" it just shows: 如果我打印变量“ foutetag”,它只会显示:

Bakkerij.Device1.DB100INT8

, like it is in the psql table. ,就像在psql表中一样。

This is how I generate the variable: 这就是我生成变量的方式:

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

Could there be anything wrong the way I generate the variable? 我生成变量的方式有什么错误吗?

If foutetag is a variable, then you need to treat it like so: 如果foutetag是一个变量,那么您需要这样对待它:

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

Also note the single = in the WHERE clause. 另请注意WHERE子句中的single =

However the INSERT statement does not accept a WHERE clause, as it will produce a new row from scratch. 但是, INSERT语句不接受WHERE子句,因为它将从头开始生成新行。 If you want to update your value, use: 如果要更新您的价值,请使用:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM