gpt4 book ai didi

database - postgresql 函数数据插入与 python

转载 作者:行者123 更新时间:2023-11-29 13:41:06 24 4
gpt4 key购买 nike

我的值(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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com