Skip to content
Advertisement

Is there a way to have SQLAlchemy NOT change 1 to True and 0 to False for BIT columns?

I am using SQLAlchemy to read data from a SQL Server database and then turning the table data to a csv file to later hand off.

However, I noticed when there is a 1 or 0 in a SQL Server table field, the csv output has True or False instead. I know to Python, it’s still a number since True == 1 returns True

Is it possible to not have this happen from the get go and have the csv keep 1 or 0?

This my current code:

JavaScript

I have about 450 tables that this would be applied to so single table solutions aren’t going to work as I need an automated way to have every table follow this rule I’m aiming for.

I started to go down the route of trying to loop through each column and change the dtype of the column but it seems easier to not have to replace True or False to 1 or 0 in the first place.

dtypes output:

JavaScript

SQL CREATE TABLE query:

JavaScript

Advertisement

Answer

As explained in

https://github.com/mkleehammer/pyodbc/issues/383

pyodbc returns bit columns as boolean values because that is what most people use bit columns for.

JavaScript

If you want pyodbc to return bit columns as some other type you can use an output converter function as illustrated in the GitHub issue. The trick is getting SQLAlchemy to use it. That is done using an event listener.

JavaScript

Edit: Or, if you use

JavaScript

you’ll get

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement