簡體   English   中英

用psycopg2遷移並返回

[英]mogrify and returning with psycopg2

我正在嘗試生成自動查詢。 我當時在考慮使用executemany,但是我需要使用returning語句,所以我做到了:

def format_bind(cols, rows):
    return '(' + '), ('.join([', '.join(['%s'] * cols)] * rows) + ')'        

def insert_many(table, values, id_column):
                if not values:
                    return []

                keys = values[0].keys()
                conn = psycopg2.connect("dbname='db' user='postgres' host='localhost' password='postgres'")
            cursor = conn.cursor()
            query = cursor.mogrify("INSERT INTO {} ({}) VALUES {} RETURNING {}".format(table,
                                                                                         ', '.join(keys),
                                                                                         format_bind(len(keys), len(values)),
                                                                                         id_column),
                                   [tuple(v.values()) for v in values])
            cursor.execute(query)
            return [t[0] for t in (cursor.fetchall())]

問題是當我執行它時,我得到: error list index out of range有人可以幫助我解決此問題嗎?

問題是我以為我必須為每個要插入的值放置一個字符串參數插值。 我會解釋一下:

假設我有一個包含2個字典(長度為3個)的列表,其中包含要插入的數據:

lst = [{'a': 21, 'b': 9, 'c': 33}, {'a': 76, 'b': 84, 'c': 46}]

為了插入這些值,我做了類似的事情:

query = curs.mogrify("INSERT INTO {} ({}) VALUES {} RETURNING {}".format(
                        table,
                        ', '.join(lst[0].keys()),
                        ', '.join(['%s'] * len(lst[0].values())),
                        'id'
                    ), [tuple(v.values()) for v in lst])

總共添加三個'%s' (在lst的單個字典中每個項一個)。 這樣做的結果是異常消息error list index out of range並且發生這種情況是因為curs.mogrify()期望lst每個字典一個'%s' ,因此在這種情況下,它只需要兩個'%s'三。

因此,從lst插入數據的正確格式為:

query = curs.mogrify("INSERT INTO {} ({}) VALUES {} RETURNING {}".format(
                            table,
                            ', '.join(lst[0].keys()),
                            ', '.join(['%s'] * len(lst)),
                            'id'
                        ), [tuple(v.values()) for v in lst])

len(lst[0].values())替換len(lst[0].values()) len(lst)

這就是我解決問題的方式(我不明白這一點,因為我沒有正確閱讀示例的代碼)。 我希望這有幫助。

山姆

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM