Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Why is it that pyodbc converts a bit data type to boolean? #383

Closed
km123456 opened this issue May 3, 2018 · 2 comments
Closed

Why is it that pyodbc converts a bit data type to boolean? #383

km123456 opened this issue May 3, 2018 · 2 comments

Comments

@km123456
Copy link

km123456 commented May 3, 2018

Why is it that pyodbc converts a bit data type to boolean?
As best I can tell this appears to be the standard behavior based on the documentation on this site.
Why not keep that value literally what it is - a 1 or 0 number data type?

Is there an easy way - setting, function, etc. to control this behavior with pyodbc?

@gordthompson
Copy link
Collaborator

gordthompson commented May 3, 2018

From what I've seen, the most common use of a BIT column is for storing Boolean values, at least on SQL Server. pyodbc probably maps BIT to Boolean because that's what most people want.

If you want something else then you can use an output converter function like this

def handle_bit_type(bit_value):
    return bit_value

for which code like this

cnxn = pyodbc.connect(conn_str)
cnxn.add_output_converter(pyodbc.SQL_BIT, handle_bit_type)
crsr = cnxn.cursor()
print(crsr.execute("SELECT CAST(1 AS BIT)").fetchval())

will print b'\x01' instead of True. You can modify the function to return some other value if that's your preference.

@mkleehammer
Copy link
Owner

It might have been a good idea, but it has been this way so long I couldn't change it if we wanted to.

In the ODBC specification there are data types like SQL_BIT but there isn't one specifically for Booleans. Other interfaces like ADO.NET convert to Boolean so I assumed that's what SQL_BIT was really mean to be. (And it might be.). IIRC, some databases that have a bool type tend to map the to SQL_BIT, so there would be complaints the other way if a Boolean type was not True and False.

The best case would have been if ODBC had both SQL_BIT and SQL_BOOL types.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants