将PDF保存到数据库中并从中提取BLOB

时间:2019-02-18 15:07:52

标签: python database pdf blob

我想将PDF作为BLOB保存在数据库中。然后第二步是将BLOB从数据库中提取回PDF。到目前为止,这是我的代码。

import mysql.connector
from mysql.connector import Error
from mysql.connector import errorcode

connection = mysql.connector.connect(host="<ip>", user='<name>', password='', db='brs')

class db_handler():


    def convert_to_binary(self, filename):
        #Convert digital data to binary format
        with open(filename, 'rb') as file:
            binaryData = file.read()
        return binaryData


    def convert_from_binary(self, filename, data):
        # Convert binary data to proper format and write it on Hard Disk
        with open(filename, 'wb') as file:
            file.write(data)


    def stored_pdf(self, filename):
        print("Inserting BLOB into python_employee table")
        try:
            cursor = connection.cursor(prepared=True)
            pdf_file = self.convert_to_binary(filename)

            # Convert data into tuple format
            insert_blob_tuple = (pdf_file)
            result  = cursor.execute("INSERT INTO pdf (pdf_file) VALUES (%s)", (insert_blob_tuple,))
            connection.commit()
            print("Image and file inserted successfully as a BLOB into python_employee table", result)

        except mysql.connector.Error as error:
            connection.rollback()
            print("Failed inserting BLOB data into MySQL table {}".format(error))

        finally:
            #closing database connection.
            if(connection.is_connected()):
                cursor.close()
                connection.close()
                print("MySQL connection is closed")


    def get_pdf(self, pdf_id, filename):
        print("Reading BLOB data from python_employee table")
        try:
            cursor = connection.cursor(prepared=True)
            sql_fetch_blob_query = """SELECT pdf_file from pdf where id_pdf = %s"""
            cursor.execute(sql_fetch_blob_query, (pdf_id, ))
            record = cursor.fetchall()
            for row in record:
                data = row[0]
                print("Storing pdf file on disk \n")
                self.convert_from_binary(filename, data)
        except mysql.connector.Error as error :
            connection.rollback()   
            print("Failed to read BLOB data from MySQL table {}".format(error))
        finally:
            #closing database connection.
            if(connection.is_connected()):
                cursor.close()
                connection.close()
                print("MySQL connection is closed")


    def main(self):
        pass


if __name__ == "__main__":
    test = db_handler()
    test.stored_pdf(r"<path>")
    #test.get_pdf(6, "gok.pdf")

当我执行此脚本时,会将PDF作为二进制文件放入数据库中,然后我要提取该文件并将其转换为PDF。它似乎可以正常工作,但是当我打开PDF时,它会打开并警告它已损坏。

0 个答案:

没有答案