我的价值观

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

我有一个postgresql函数merge_db()的名字,它有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'占位符”
我不清楚如何将用户值作为合并参数发送。
任何帮助都将不胜感激。
谢谢。

最佳答案

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 - 用python插入postgresql函数数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55355080/

10-12 03:07