database - postgresql 函数数据插入与 python

标签 database python-3.x postgresql function insert

我的值(value)观

user = [[34, 'Victoria', '17:34:50', None], [40, 'Meherin', '00:04:00', '23:56:10'], [30, 'Micahle', '18:58:43', None]]

我有一个名为 merge_db() 的 postgresql 函数,它有 4 个参数。现在我想用 python 从用户插入值。

postgresql 函数。

CREATE FUNCTION merge_db(id1 integer, name1 character varying, login1 time, logout1 time) RETURNS VOID AS
$$
BEGIN
    LOOP
        -- first try to update the id
        UPDATE my_company SET (name, login, logout) = (name1, login1, logout1) WHERE id = id1;
        IF found THEN
            RETURN;
        END IF;
        -- not there, so try to insert the key
        -- if someone else inserts the same key concurrently,
        -- we could get a unique-key failure
        BEGIN
            INSERT INTO my_company(id, name, login, logout) VALUES (id1, name1, login1, logout1);
            RETURN;
        EXCEPTION WHEN unique_violation THEN
            -- Do nothing, and loop to try the UPDATE again.
        END;
    END LOOP;
END;
$$
LANGUAGE plpgsql;

我的python代码是这样的

insert_query = "SELECT merge_db(%s) values %s"
execute_values(cur, insert_query, user)
conn.commit()

在这种情况下抛出 ValueError “ValueError:查询包含多个 '%s' 占位符”

我不清楚如何将用户值作为 merger_db 参数发送。

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

最佳答案

for i in user:
        print(i[0], i[1], i[2], i[3], )
        insert_query = "SELECT merge_db({}, '{}', '{}', '{}')".format(i[0], i[1], i[2], i[3]
cur.execute(insert_query)

它会很好用,但会引发重复键错误。

关于database - postgresql 函数数据插入与 python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55355080/

相关文章:

javascript - 用php和sql编写有关数据库连接的伪代码

ruby - 如何获得数字数据类型以与 postgresql 和 Sequel ORM 一起使用?

postgresql - 短语搜索运算符 <-> 是否适用于 JSONB 文档或仅适用于关系表?

java - 通过hibernate映射将数据插入数据库表失败

mysql - 数据库:我可以在第三范式数据库中拥有可为空的属性吗?

python - 索引错误 : list out of range in a while loop

python-3.x - Elasticsearch 搜索字段

python - 如何通过代码将用户明智的销售订单与网站菜单链接起来

postgresql - 如何在触发器过程中使用动态 sql 设置复合类型列

java - 如何创建其中包含 MySQL 数据库的可执行文件?