簡體   English   中英

Python:插入字符串時格式錯誤的數組文字

[英]Python: malformed array literal when inserting a string

我正在嘗試從文件中讀取並使用psycopg2將數據插入python中的postgresql表。

這是我寫的函數:

def insert(file, table, col, conn):
    sql = "INSERT INTO "+table+"("+col+") VALUES(%s)"
    cur = conn.cursor()
    with open(os.path.join(DEFAULTS_FOLDER, file)) as fp:
        line = fp.readline()
        while line:
            cur.execute(sql, (line.rstrip(),))
            line = fp.readline()
        conn.commit()
        cur.close()
    return

出於某種原因,我收到一個錯誤:

cur.execute(sql, (line.rstrip(),)) psycopg2.DataError: malformed array literal: "hello" LINE 1: INSERT INTO greetings(gname) VALUES('hello')

我也試圖插入一個普通的字符串,我仍然得到相同的錯誤。

錯誤消息表示表greetings的列gname是數組,而不是純文本。 如果是文本數組,則查詢應如下所示:

INSERT INTO greetings(gname) VALUES('{hello}')

您應該更改代碼的相關片段,例如:

cur.execute(sql, ("{{{}}}".format(line.rstrip()),))

暫無
暫無

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

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