'How to use pandas.read_sql but keep RowVersion formatting?
I've been struggling since the morning with this. I have a SQL table with a RowVersion column, that I'm creating using the following code:
mycursor = cnxn.cursor()
s = """
CREATE TABLE table_name (
PersonID int PRIMARY KEY,
Name varchar(255),
RowVersion rowversion);
"""
mycursor.execute(s)
sql = "INSERT INTO table_name (PersonID, Name) VALUES (?, ?)"
val = [
(1, 'Andres'),
(2, 'Carl'),
(3, 'Tracy'),
]
mycursor.executemany(sql, val)
cnxn.commit()
Output table:
| PersonID | Name | RowVersion |
|---|---|---|
| 1 | Andres | AAAAAAAAD70= |
| 2 | Carl | AAAAAAAAD74= |
| 3 | Tracy | AAAAAAAAD78= |
But once I read the table using pd.read_sql or pd.read_sql_query the column changes to the following:
dfTable = pd.read_sql("SELECT * FROM table_name", cnxn, coerce_float=False)
dfTable.head()
| PersonID | Name | RowVersion |
|---|---|---|
| 1 | Andres | b'\x00\x00\x00\x00\x00\x00\x0f\xba' |
| 2 | Carl | b'\x00\x00\x00\x00\x00\x00\x0f\xbb' |
| 3 | Tracy | b'\x00\x00\x00\x00\x00\x00\x0f\xbc'' |
What I would like to get is to keep the RowVersion format as before. According to the pd.read_sql documentation there is a way to avoid converting non-string values to floating points, but since it is a hex value pandas is reading as a string.
Is there a workaround to find a solution?
Thank you,
Solution 1:[1]
I ended up reading and altering the table again after uploading the Dataframe as table...
s = """
ALTER TABLE [dbo].[table_name] ADD rv rowversion NULL
"""
mycursor.execute(s)
cnxn.commit()
Please, feel free to answer if there is another solution, ty.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
