Python的psycopg2和pgAdmin4如何检索字节数据



我已经上传了一个带有bytes((函数的jpg图像到byta字段。

插入代码

conn = None
try:
# read data from a picture
imagen = open("imagen.jpg", "rb").read()
# connect to the PostgresQL database
conn = psycopg2.connect(host="localhost", database="test", user="postgres", password="admin")
# create a new cursor object
cur = conn.cursor()
# execute the INSERT statement
cur.execute("INSERT INTO nuevotest(id,data) " +
"VALUES(%s,%s)",
(1, bytes(imagen)))
# commit the changes to the database
conn.commit()
# close the communication with the PostgresQL database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()

选择代码:

conn = None
try:
conn = psycopg2.connect(host="localhost", database="test", user="postgres", password="admin")
# create a new cursor object
cur = conn.cursor()
# execute the INSERT statement
cur.execute(""" SELECT data
FROM nuevotest
WHERE id=1 """,
)
# commit the changes to the database
conn.commit()
imagen = cur.fetchall()
print(type(imagen))
print(imagen)
# close the communication with the PostgresQL database
cur.close()
except (Exception, psycopg2.DatabaseError) as error:
print(error)
finally:
if conn is not None:
conn.close()

但我所期望的是一个带有字节码的列表或元组,而不是这个:

PyCharm控制台带有(内存方向?idk(

我不知道该怎么做。

取决于检索数据后的计划。正如@adrian_klaver所说,您可以使用缓冲区来写入输出。像这样,你会把它发送到一个文件:

with open(your_output_file, 'wb') as im:
im.write(the_in_memory_data)

使用PIL,您可以将其输出到系统的图像查看器,而无需保存。

最新更新