簡體   English   中英

使用 psycopg2 插入 Postgres 表的值錯誤

[英]Value error inserting into Postgres table with psycopg2

我一直在嘗試使用這段代碼:

# df is the dataframe
if len(df) > 0:
df_columns = list(df)
# create (col1,col2,...)
columns = ",".join(df_columns)

# create VALUES('%s', '%s",...) one '%s' per column
values = "VALUES({})".format(",".join(["%s" for _ in df_columns])) 

#create INSERT INTO table (columns) VALUES('%s',...)
insert_stmt = "INSERT INTO {} ({}) {}".format(table,columns,values)

cur = conn.cursor()
cur = db_conn.cursor()
psycopg2.extras.execute_batch(cur, insert_stmt, df.values)
conn.commit()
cur.close()

所以我可以連接到 Postgres DB 並從 df 插入值。

我收到此代碼的這 2 個錯誤:

LINE 1: INSERT INTO mrr.shipments (mainFreight_freight_motherVesselD...

psycopg2.errors.UndefinedColumn: column "mainfreight_freight_mothervesseldepartdatetime" of relation "shipments" does not exist

由於某種原因,列無法正確獲取值

我能做些什么來修復它?

你不應該自己做字符串插值; 讓 psycopg2 處理它。 文檔

警告 永遠,永遠,永遠不要使用 Python 字符串連接 (+) 或字符串參數插值 (%) 將變量傳遞給 SQL 查詢字符串。 甚至不是在槍口下。

由於您還有動態列名,您應該使用psycopg2.sql創建語句,然后使用將查詢參數傳遞給 psycopg2 的標准方法而不是使用格式。

暫無
暫無

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

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