2

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()
Crn
  • 45
  • 1
  • 8

1 Answers1

0

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)
Gord Thompson
  • 116,920
  • 32
  • 215
  • 418
  • And also, if you could help, if I want to convert into floating point numbers, would that be better to do it in HEX bytes or varbinary(max) ? – Crn Feb 21 '19 at 23:38
  • @RCan - I'm not sure what you mean. Take a `varbinary`-like column and interpret it as `float` (or similar)? In any case, that would be a [separate question](https://stackoverflow.com/questions/ask). – Gord Thompson Feb 22 '19 at 01:11