Search code examples
pythonsqlinsertpyodbctruncate

Pyodbc - Insert query Truncated


I am new to python, trying to run a piece of code, where i am dynamically assigning columns and its values to an insert query, it can be a query with 4 columns and 4 values inserted or 2 columns with 2 values

INSERT INTO dbo.MYDB ('COL1','COL2','COL3') VALUES ('A','B','C')

my problem is small queries run fine, but bigger queries are truncated

this is a good one which ran

INSERT INTO dbo.CUST (CUSTNAME,AGE,CITY) VALUES (?,?,?)

and this is the one which got truncated and hence failed (notice 3rd column truncated QUAN...)

INSERT INTO dbo.FACT (CUSTNAME,PRODUCTNAME,QUAN... VALUES (?,?,?,?)

I am storing this query in a variable (named query) and passing it to be executed like below

cursor.executemany(query, (values))

when i hover over this variable 'query', it says its type as - (variable) query: Any


Solution

  • This is obviously df.to_sql()

    Here's one example:

    DataFrame.to_sql(self, name, con, schema=None, if_exists='fail', index=True, index_label=None, chunksize=None, dtype=None, method=None)

    See the link before for more details.

    https://www.w3resource.com/pandas/dataframe/dataframe-to_sql.php

    If it doesn't work for you on the first try, keep at it. This is an amazing function, and it will do exactly what you want. Also, see the link below.

    https://pandas.pydata.org/docs/user_guide/merging.html