简体   繁体   English

Python 与 psycopg2 和 pgAdmin4 我如何检索 bytea 数据

[英]Python with psycopg2 and pgAdmin4 how can i retrieve bytea data

I have uploaded a jpg image with the bytes() function to the bytea field.我已将带有 bytes() function 的 jpg 图像上传到 bytea 字段。

INSERT CODE插入代码

 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()

SELECT CODE: SELECT 代码:

    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()

But what i was expectiong was a list or tuple with the byte code, not this:但我所期待的是一个带有字节码的列表或元组,而不是这个:

PyCharm console with a (memory direction? idk) PyCharm控制台带一个(内存方向?idk)

I have no idea how to work with that.我不知道如何使用它。

Depends on what you are planning on doing after you retrieve the data.取决于您在检索数据后打算做什么。 As @adrian_klaver said, you can use a buffer to write the output.正如@adrian_klaver 所说,您可以使用缓冲区来写入 output。 Like this you would send it to a file:像这样,您将其发送到文件:

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

Using PIL you can output it to the image viewer of the system without saving it.使用 PIL,您可以将其 output 到系统的图像查看器而不保存它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM