我在理解psycopg3Python 庫的適當語法時有點困難。我正在嘗試將 .csv 檔案的內容復制到我的資料庫中。PostgreSQL 檔案表明copy應該寫成如下:
COPY table_name [ ( column_name [, ...] ) ]
FROM { 'filename' | PROGRAM 'command' | STDIN }
[ [ WITH ] ( option [, ...] ) ]
[ WHERE condition ]
所以我寫了我的python陳述句如下:
import psycopg
with psycopg.connect('dbname=ideatest user=postgres password=password') as conn:
with conn.cursor() as cur:
mock_idea_info = open(r'C:\dir\filename.csv')
cur.copy('public.ideastorage FROM C:\dir\filename.csv;')
print('Copy successful.')
問題是腳本列印“復制成功”,但沒有將資料插入資料庫。不會生成錯誤訊息。我在檔案路徑中復制了 \ 字符,所以這不是問題。我一直在尋找解決方案和可能的故障排除方法,但還沒有找到任何我理解的似乎相關的東西。
另外,有什么辦法可以mock_idea_info直接傳遞到copy陳述句中嗎?
任何幫助將不勝感激。
uj5u.com熱心網友回復:
我沒有看到您承諾在輸入后將資料保存在資料庫中。嘗試添加這個:
conn.commit()
uj5u.com熱心網友回復:
見復制自:
cat data.out
1 2
2 1
\d csv_test
Table "public.csv_test"
Column | Type | Collation | Nullable | Default
-------- --------- ----------- ---------- ---------
col1 | integer | | |
col2 | integer | | |
with open("data.out", "r") as f:
with cur.copy("COPY csv_test FROM STDIN") as copy:
while data := f.read(100):
copy.write(data)
con.commit()
select * from csv_test ;
col1 | col2
------ ------
1 | 2
2 | 1
--Add format options
cat data.out
1,2
2,1
with open("data.out", "r") as f:
with cur.copy("COPY csv_test FROM STDIN WITH (FORMAT CSV)" ) as copy:
while data := f.read(100):
copy.write(data)
con.commit()
select * from csv_test ;
col1 | col2
------ ------
1 | 2
2 | 1
1 | 2
2 | 1
以上改編自鏈接中的示例。這while data := f.read(100)使用了:=僅在 Python 3.8 中可用的 walrus( )
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/350381.html
標籤:Python 数据库 PostgreSQL 复制 psycopg2
下一篇:合并2個PostgreSQL表
