Meraj Hussain
Meraj Hussain

Reputation: 362

How to insert data into unique identifier column into SQL Server using pyodbc

I have a table that has a column of type uniqueidentifier. How do I insert the data into uid columns using pyodbc?

I am trying this code:

 cursor.execute("""
                   Insert into tablename (col1,col2)
                   values (?,?)
                """, 
               '67E616B4-7DBC-6D14-B0BA-0F7DE2F94AEE',
               '2E92D02D-B7DA-4DED-9816-26B2CF867FA2' )

col1 and col2 are of type uniqueidentifier.

I get this error:

pyodbc.ProgrammingError: ('42000', '[42000] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Conversion failed when converting from a character string to uniqueidentifier. (8169) (SQLExecDirectW)')

Upvotes: 1

Views: 1849

Answers (1)

Barbaros Özhan
Barbaros Özhan

Reputation: 65408

You can use fast_to_sql which is an improved way to upload pandas dataframes to Microsoft SQL Server such as

df = pd.DataFrame({
"col1": ['67E616B4-7DBC-6D14-B0BA-0F7DE2F94AEE'],
"col2": ['2E92D02D-B7DA-4DED-9816-26B2CF867FA2']
})
    
 fts.fast_to_sql(df, "tablename", conn, if_exists="append", custom=None, temp=False)

where append option stands for inserting new values to the table

Upvotes: 1

Related Questions