<p>Much better solution for modern versions of mySQL: skip the base64 encoding, and use <code>_binary %s</code> to send binary data, or just add <code>binary_prefix = True</code> option when setting up the pymysql connection. For example, </p>

<pre><code>import pymysql
import requests

myPDF = requests.get("https://arxiv.org/pdf/2004.00627.pdf")
conn = pymysql.connect(
  host          = "127.0.0.1",
  user          = user,
  passwd        = password,
  db            = "myDB",
  binary_prefix = True)
cur = conn.cursor()

insertLine = "INSERT INTO myDB (PDF) VALUES (%s)"
cur.execute(insertLine, myPDF)
conn.commit()  
</code></pre>
write scraped binary file to blob without first writing it to disk
<p>I use the <code>requests</code> library to retrieve a binary file from a website. I now want to store it in MySQL as a BLOB. I don't want to take the intermediate step of writing the file to disk. What is the best way to do this?</p>

<p>At present, I am using <code>base64</code> to encode the binary file so that MySQL will accept it, as in <a href="https://stackoverflow.com/a/46093925/697473">this suggestion</a>. Is this the best strategy, or is there a way that permits me to skip the encoding (and the subsequent decoding when I retrieve the file)?</p>

<p>Minimal example:</p>

<pre><code>import base64
import pymysql
import requests

myPDF = requests.get("https://arxiv.org/pdf/2004.00627.pdf")
myPDF_encoded = base64.b64encode(myPDF.content)
conn = pymysql.connect(
  host   = "127.0.0.1",
  user   = user,
  passwd = password,
  db     = "myDB")
cur = conn.cursor()

insertLine = "INSERT INTO myDB (PDF) VALUES (%s)"
cur.execute(insertLine, myPDF_encoded)
conn.commit()          
</code></pre>

<p>Many posts speak to the general problem of writing a binary file to a BLOB, but as best I can tell, all start from the assumption that the file is to be read from disk.</p>