![](/img/trans.png)
[英]How to download images from postgres bytea column using R or python?
[英]Download files from bytea column in postgresql with python
我可以從 python 中的列類型 bytea 從我的數據庫中下載文件嗎?
我正在嘗試使用 psycopg2,我上傳了一個 .txt 文件,但是當我嘗試將它檢索到我的本地計算機時,它只是保存了一個包含不可讀數據的 .txt 文件,該 txt 文件的開頭是這樣的“U0ZUUCBhZGRy.txt”。 ...”所以看起來像字節信息,與數據庫保存的相同。
dbeaver example_dbeaver_column中的數據庫截圖
這是我使用的代碼。
import psycopg2
connection = psycopg2.connect(dbname=dbname,
host=host,
port=port,
user=user,
password=password)
# get cursor
cursor = connection.cursor()
query = "select c.file from my_table t where t.file_name = 'credentials.txt'"
cursor.execute(query)
data = cursor.fetchall()
file_binary=data[0][0].tobytes()
with open('my_text.txt','wb') as file:
file.write(file_binary)
有什么想法可以解決這個問題嗎?
謝謝你的幫助
我找到了! 在 postgre 它是用 base64 編碼的,所以我需要用 base64 庫解碼。
import base64
import psycopg2
connection = psycopg2.connect(dbname=dbname,
host=host,
port=port,
user=user,
password=password)
# get cursor
cursor = connection.cursor()
query = "select c.file from my_table t where t.file_name = 'credentials.txt'"
cursor.execute(query)
data = cursor.fetchall()
file_binary=data[0][0].tobytes()
with open('my_text.txt','wb') as file:
file.write(base64.b64decode(file_binary))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.