1

I'm attempting to insert data from a pandas dataframe into an MSSQL database table.

This is my code that's throwing an error

resultDf.to_sql(name='obscured',schema='dbo',if_exists='append', con=write_engine, index=True,chunksize=1500, method='multi')

This code worked/works

resultDf.head().to_sql(name='obscured',schema='dbo',if_exists='append', con=write_engine, index=True)

This is the error that I'm getting which according to sql alchemy's documentation is thrown by pyodbc, which is the driver I'm using for MSSQL.

DBAPIError: (pyodbc.Error) ('07002', '[07002] [Microsoft][ODBC Driver 17 for SQL Server]COUNT field incorrect or syntax error (0) (SQLExecDirectW)')
[SQL: INSERT INTO dbo.obscured ([obscuredcolumn1], [obscuredcolumn2], [obscuredcolumn3], [obscuredcolumn4], [obscuredcolumn5], [obscuredcolumn6], [obscuredcolumn7], [obscuredcolumn8], [obscuredcolumn9]) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?), (?, ?, ?, ?, ?, ?, ?, ?, ?)

there's probably 1500 or so tuples of ?, then 1500 or so tuples of actual values:

[parameters: (datetime.datetime(2022, 8, 9, 15, 0), 7179747, 868, 920, 0, 0, 0, 0, 0, datetime.datetime(2022, 8, 9, 15, 0), 7179748, 0, 430, 0, 0, 0, 0, 0, datetime.datetime(2022, 8, 9, 15, 0)

Where have I gone wrong? What should I be testing to troubleshoot?

4
  • 1
    Can you check if resultDf contains any empty strings '' ? It seems that the PYODBC driver can't handle empty strings. Maybe the reason why you can push resultDf.head() to the MSSQL database table is that because the first five rows of resultDf doesn't carry any empty string. Commented Sep 9, 2022 at 22:00
  • All columns are cast as type ‘int32’ Commented Sep 10, 2022 at 0:32
  • Got a some solution regarding the question Commented Sep 18, 2022 at 15:14
  • Follow this link : stackoverflow.com/questions/37161574/… Commented Sep 18, 2022 at 15:17

1 Answer 1

1

It's related to chunksize. I shrunk the chunksize from 1500 to 50, then gradually increased. There must be a setting on the database side that's limiting the number of records that can be inserted at one time.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.