Search code examples
pythonsqltype-conversionpyodbcvarbinary

Python Pyodbc Binary Column is returning \xda\x08\xcd\x08\xba\x08 instead of numbers


I have a SQL database that displays a varbinary (max) like this 0x9406920691068F... I want to import it to python pycharm to get the same exact type of data. However, it shows something like this instead [b'\x94\x06\x92\x06\x91\x06\x8f\x06\x8d.. how do I copy the same numbers to python? I am a beginner in python, please help.

I copied the code from previous post and it didn't work

import pyodbc

    def hexToString(binaryString):
    try:
      hashString = ["{0:0>2}".format(hex(b)[2:].upper()) for b in binaryString]
      return '0x' + "".join(hashString)
    except:
      return binaryString


    query = """ select P from Access.table """

conn_str = (
      **** private database details # I don't copy on the page
    )

cnxn = pyodbc.connect(conn_str)
cnxn.add_output_converter(pyodbc.SQL_BINARY, hexToString)
cursor = cnxn.cursor()

try:
    cursor.execute(query)
    row = cursor.fetchone()
except MySQLdb.error as err:
    print(err)
else:
    while row is not None:
        print(row)
        row = cursor.fetchone()

Solution

  • If the column return type is varbinary(max) then you need to add the output converter function to handle SQL_VARBINARY, not SQL_BINARY

    cnxn.add_output_converter(pyodbc.SQL_VARBINARY, converter_function_name)