Error while insert dataframe to Sql-server DB using to_sql function in python

Viewed 4361

I am trying to insert pandas dataframe df into SQL Server DB using dataframe.to_sql function. But i getting below error:

Source code:

import pyodbc
import sqlalchemy
import urllib

df  #sample dataframe
params = urllib.parse.quote_plus("DRIVER={SQL Server};SERVER=GIRSQL.GIRCAPITAL.com;DATABASE=Tableau;UID=SQL_User;PWD=pass")
engine = sqlalchemy.create_engine("mssql+pyodbc:///?odbc_connect=%s" % params)
engine.connect()
df.to_sql(name='[Tableau].[dbo].[Test table]',con=engine, index=False, 
if_exists='append')

Error:

File "C:\Users\Arvinth\sqlalchemy\engine\default.py", line 470, in do_execute cursor.execute(statement, parameters)

sqlalchemy.exc.ProgrammingError: (pyodbc.ProgrammingError) ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near 'INTEGER'. (102) (SQLExecDirectW)") [SQL: '\nCREATE TABLE [[Tableau].[dbo].[Test table]] (\n\t[A] INTEGER NULL, \n\t[B] INTEGER NULL, \n\t[C] INTEGER NULL\n)\n\n']

Sample dataframe:

    A  B  C
 0  0  0  0
 1  1  1  1
 2  2  2  2
 3  3  3  3
 4  4  4  4
 5  5  5  5
 6  6  6  6
 7  7  7  7

Can anyone please help solve the issue.

2 Answers

Maybe you can refer the table in to_sql():

df.to_sql('test_table',con=engine, index=False, if_exists='append')
Related