title: Inserting pyodbc.Binary data (BLOB) into SQL Server image column
body: <p>I am trying to insert binary data into a column of <code>image</code> datatype in a SQL Server database. I know <code>varbinary(max)</code> is the preferred data type, but I don't have rights to alter the schema.</p>
  
  <p>Anyhow, I am reading the contents of a file and wrapping it in pyodbc.Binary() as below:</p>
  
  <pre><code>f = open('Test.ics', 'rb')
  ablob = f.read().encode('hex')
  ablob = pyodbc.Binary(ablob)
  </code></pre>
  
  <p>When I <code>print repr(ablob)</code> I see the correct value <code>bytearray(b'424547494e3a5 . . .</code> (ellipsis added).</p>
  
  <p>However, after inserting </p>
  
  <pre><code>insertSQL = """insert into documents(name, documentType, document, customerNumber) values(?,?,?,?)"""
  cur.execute(insertSQL, 'test200.ics', 'text/calendar', pyodbc.Binary(ablob), 1717)
  </code></pre>
  
  <p>The value of the document column is <code>0x343234353 . . .</code> which appears as if the hexadecimal data was converted to ASCII character codes.</p>
  
  <p>I thought wrapping the value in pyodbc.Binary() would take care of this? Any help would be greatly appreciated.</p>
  
  <p>I am using Python 2.7 and SQL Server 2008 R2 (10.50).</p>
  
  <p><strong>Edit</strong>:</p>
  
  <p>beargle kindly pointed out that I was needlessly calling encode('hex'), which was leading to my issue. I believe this must have been coercing the data into a string (although a fuller explanation would be helpful).</p>
  
  <p>Working code:</p>
  
  <pre><code>ablob = pyodbc.Binary(f.read())
  cur.execute(insertSQL, 'test200.ics', 'text/calendar', ablob, 1717)
  </code></pre>