添加链接
link管理
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
相关文章推荐
焦虑的柳树  ·  Amazon Redshift ...·  1 周前    · 
踢足球的帽子  ·  Psycopg2 vs Psycopg3 ...·  4 天前    · 
一直单身的烈酒  ·  Three.js ...·  10 月前    · 
满身肌肉的水桶  ·  用VB.NET连接ORACLE ...·  10 月前    · 

摘要 :在本教程中,您将学习如何在 Python 中处理 PostgreSQL BLOB 数据。

SQL 标准将 BLOB 定义为用于在数据库中存储二进制数据的二进制大对象。使用 BLOB 数据类型,您可以将图片、文档等内容存储到表中。

PostgreSQL 不支持 BLOB,但您可以使用 BYTEA 数据类型来存储二进制数据。

我们来看一下 part_drawings 表。

part_drawings 表在 drawing_data 列中存储了部件的图片。我们将向您展示如何将二进制数据插入此列并将其读回。

将 BLOB 插入表中

要将 BLOB 数据插入表中,请使用以下步骤:

  • 首先,从文件中读取数据。
  • 接下来,通过从 connect() 函数创建新的连接对象来 连接到 PostgreSQL 数据库
  • 然后,从该 connection 对象创建一个 cursor 对象。
  • 之后,使用输入值执行 INSERT 语句。对于 BLOB 数据,您需要使用 psycopg 模块的 Binary 对象。
  • 最后,通过调用 connection 对象的 commit() 方法,将更改永久提交到 PostgreSQL 数据库。
  • 下面的 write_blob() 函数,从 path_to_file 参数指定的文件中读取二进制数据,并将其插入到 part_drawings 表中。

    #!/usr/bin/python
    import psycopg2
    from config import config
    def write_blob(part_id, path_to_file, file_extension):
        """ insert a BLOB into a table """
        conn = None
        try:
            # read data from a picture
            drawing = open(path_to_file, 'rb').read()
            # read database configuration
            params = config()
            # connect to the PostgresQL database
            conn = psycopg2.connect(**params)
            # create a new cursor object
            cur = conn.cursor()
            # execute the INSERT statement
            cur.execute("INSERT INTO part_drawings(part_id,file_extension,drawing_data) " +
                        "VALUES(%s,%s,%s)",
                        (part_id, file_extension, psycopg2.Binary(drawing)))
            # 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()
    

    下面的代码片段调用 write_blob() 函数两次,以将两个新部件和相应图片文件的二进制数据插入到 part_drawings 表中。

    if __name__ == '__main__':
        write_blob(1, 'images/simtray.jpg', 'jpg')
        write_blob(2, 'images/speaker.jpg', 'jpg')
    

    读取表中的 BLOB

    从表中读取 BLOB 的步骤与从表中查询数据的步骤类似。从表中获取二进制数据后,我们可以保存到文件、输出到网络浏览器等。

    下面的 read_blob() 函数根据指定的部件 ID 从 part_drawings 表中查询 BLOB 数据,并将 BLOB 数据保存到文件中。

    def read_blob(part_id, path_to_dir):
        """ read BLOB data from a table """
        conn = None
        try:
            # read database configuration
            params = config()
            # connect to the PostgresQL database
            conn = psycopg2.connect(**params)
            # create a new cursor object
            cur = conn.cursor()
            # execute the SELECT statement
            cur.execute(""" SELECT part_name, file_extension, drawing_data
                            FROM part_drawings
                            INNER JOIN parts on parts.part_id = part_drawings.part_id
                            WHERE parts.part_id = %s """,
                        (part_id,))
            blob = cur.fetchone()
            open(path_to_dir + blob[0] + '.' + blob[1], 'wb').write(blob[2])
            # 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()
    

    以下代码片段读取 id 值为 1 和 2 的部件的二进制数据,并将二进制数据保存到文件夹 images/blob 中。

    在本教程中,您学习了如何在 Python 中使用 psycopg 数据库适配器处理 PostgreSQL BLOB 数据。