Python Forum
[Solved] Retrieving a pdf from sqlite3 - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: [Solved] Retrieving a pdf from sqlite3 (/thread-36635.html)



[Solved] Retrieving a pdf from sqlite3 - BigMan - Mar-12-2022

What I am trying to do
pdf files are stored in my sqlite3 database as blobs.
I want to select one specific pdf file and save it as a file.

That's my python error message:
sqlite3.OperationalError: Could not decode to UTF-8 column 'dokument' with text '%PDF-1.2

What's my python code
I tried a lot, also copied and paste a lot from the internet. I assume it's less an issue of the code, but more that I forget something on a higher level (e.g. sqlite3 configuration)?
Anyhow: the very latest code I work with:

def readBlobData_and_safe_as_file(path_to_db, select_query):
    con = sqlite3.connect(path_to_db)
    cur = con.cursor()

    with open("/home/Datei.pdf", "wb") as output_file:
        cur.execute(select_query)
        blobdat = cur.fetchone()
        output_file.write(blobdat[0])
        cur.close()
        con.close()
After one week of try-and-error, you can't believe how grateful I would be for support. Millions thanks in advance.
(remark: I am not a professionel programer, I do this for fun and as a hobby).


RE: Retrieving a pdf from sqlite3 - Gribouillis - Mar-12-2022

Have you tried the solutions from this page? for example setting conn.text_factory = bytes


RE: Retrieving a pdf from sqlite3 - BigMan - Mar-12-2022

(Mar-12-2022, 07:28 AM)Gribouillis Wrote: Have you tried the solutions from this page? for example setting conn.text_factory = bytes

Holly sh****, this single addiional line (con.text_factory = bytes) solved it. Thank you, thank you thank you!!! You are my hero! Great!!!


RE: [Solved] Retrieving a pdf from sqlite3 - ndc85430 - Mar-12-2022

Why do you want to store the PDFs in the database in the first place? Wouldn't it make more sense to save the files and store the paths to them in the database instead?


RE: [Solved] Retrieving a pdf from sqlite3 - deanhystad - Mar-12-2022

Files are so last century.