I am trying to use Pandas and Sql Alchemy. This is basically what I am trying to do. If I drop the table, it will create it but I want it to append and not have to do table renaming. I have tried updating and changing versions of all the libraries. I am at a loss. If I start with no table it creates it, then i run the code again and it crashes. The error message just says the table already exists, which I know, that is why I am telling it to append. Also, before the load i am reading data using PYMSSQL and it reads fine to a dataframe
Python Command
def writeDFtoSSDatabase(tgtDefiniton,df):
try:
if int(tgtDefiniton.loadBatchSize) > 0:
batchSize = int(tgtDefiniton.loadBatchSize)
else:
batchSize = 1000
#Domain error using SQL Alchemy
logging.debug("Writting Dataframe to SQL Server database")
#hardcoded type beccause that is only type for now
with createDBConnection(tgtDefiniton.tgtDatabaseServer
,tgtDefiniton.tgtDatabaseDatabase
,tgtDefiniton.tgtDatabaseUser
,tgtDefiniton.tgtDatabasePassword,tgtDefiniton.tgtDataType).connect().execution_options(schema_translate_map={
None: tgtDefiniton.tgtDatabaseSchema}) as conn:
logging.debug("Writting DF to Database table {0}".format(tgtDefiniton.tgtDatabaseTable))
logging.debug("ifTableExists: {0}.".format(tgtDefiniton.ifTableExists))
if tgtDefiniton.ifTableExists == "append":
logging.debug('Appending Data')
df.to_sql(tgtDefiniton.tgtDatabaseTable,con=conn,if_exists='append',chunksize = batchSize,index=False)
elif tgtDefiniton.ifTableExists == "replace":
logging.debug('Replacing Table and Data')
df.to_sql(tgtDefiniton.tgtDatabaseTable,con=conn,if_exists='replace',chunksize = batchSize,index=False)
else:
df.to_sql(tgtDefiniton.tgtDatabaseTable,con=conn,if_exists='fail',index=False)
logging.debug("Data wrote to database")
except Exception as e:
logging.error(e)
raise
Error
(Background on this error at: http://sqlalche.me/e/e3q8)
2021-08-30 13:31:42 ERROR (pymssql.OperationalError) (2714, b"There is already an object
named 'test' in the database.DB-Lib error message 20018, severity 16:\nGeneral SQL Server
error: Check messages from the SQL Server\n")
EDIT: Log Entry
2021-08-30 13:31:36 DEBUG Writting Dataframe to SQL Server database
2021-08-30 13:31:36 DEBUG create_engine(mssql+pymssql://REST OF CONNECTION INFO
2021-08-30 13:31:36 DEBUG DB Engine Created
2021-08-30 13:31:36 DEBUG Writting DF to Database table test
2021-08-30 13:31:36 DEBUG ifTableExists: append.
2021-08-30 13:31:36 DEBUG Appending Data
2021-08-30 13:31:42 ERROR (pymssql.OperationalError) (2714, b"There is already an object named 'test' in the database.DB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n")
[SQL:
execute
line of code – ApotheosistgtDefiniton.ifTableExists
is getting set correctly? It looks like you're inadvertently calling.to_sql()
withif_exists='fail'
. – Sigismondo