簡體   English   中英

無法使用psycopg2在postgres中插入None值

[英]cannot insert None value in postgres using psycopg2

我有一個包含100多個列和行的數據庫(PostgreSQL)。 表中的某些單元格為空,我使用python編寫腳本,因此None值放置在空單元格中,但是當我嘗試插入表中時顯示以下錯誤。

"  psycopg2.ProgrammingError: column "none" does not exist"

我正在使用psycopg2作為python-postgres接口............有什么建議嗎?

提前致謝......

這是我的代碼:

list1=[None if str(x)=='nan' else x for x in list1];

cursor.execute("""INSERT INTO table VALUES %s""" %list1;
);

不要使用%字符串插值,而應使用SQL參數 數據庫適配器可以很好地處理None ,它只需要轉換為NULL ,但是只有在使用SQL參數時才會發生:

list1 = [(None,) if str(x)=='nan' else (x,) for x in list1]

cursor.executemany("""INSERT INTO table VALUES %s""", list1)

我假設您正在嘗試在此處插入多行。 為此,您應該使用cursor.executemany()方法並傳遞要插入的行列表; 每行是一個元組,這里有一列。

如果list1只是一個值,請使用:

param = list1[0]
if str(param) == 'nan':
    param = None

cursor.execute("""INSERT INTO table VALUES %s""", (param,))

更加明確和易讀。

暫無
暫無

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

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