【问题标题】:SQL Insert if not exists with psycopg2如果 psycopg2 不存在 SQL 插入
【发布时间】:2015-05-29 10:47:29
【问题描述】:

我想用 python 脚本在 postgres 数据库中插入一些值, 但是当我用下面的代码尝试它时,我在第一个 IF 处遇到了语法错误。

sql_string = "BEGIN IF (NOT EXISTS(SELECT * FROM table WHERE nm=name))
            BEGIN INSERT INTO table(nm, nb)
            VALUES (%s, %s) END END"
cur.execute(sql_string, (name, number))

如果有人有想法会很好。 谢谢:)

【问题讨论】:

  • SQL 中没有IF(...)。将条件放在 where 子句中。 :INSERT INTO the_table(column_list) value_list WHERE NOT EXISTS (select 1 from same_table WHERE same_condition)
  • 该链接指向不同的数据库引擎。
  • @Dan Bracuk 这是关于 PostgreSQL 的。使用 psycopg2 从 Python 访问。

标签: python sql postgresql psycopg2


【解决方案1】:

这种方法与数据库无关。

 insert into yourtable
 (field1, field2, etc)
 select distinct value1, value2, etc
 from some_small_table
 where not exists
 (subquery to check for existing records)

【讨论】:

    猜你喜欢
    • 2018-09-17
    • 2014-01-25
    • 2019-07-13
    • 1970-01-01
    • 2021-02-19
    • 2021-02-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多