4
votes

I'm working with Python and sqlalchemy to empty tables stored in SQL Server. It seems that the SQL query, given as argument in session.execute function, simply does not execute. The table still contains data.

When I print and run the same query within SQL Server MS, it does exactly as expected.

Help is appreciated!

tableName = 'someTable'
engine = sqlalchemy.create_engine('connectionString')
Session = scoped_session(sessionmaker(bind=engine))
currentSession = Session()
query = 'IF ('
                       'EXISTS ('
                       'SELECT * FROM INFORMATION_SCHEMA.TABLES '
                       'WHERE TABLE_SCHEMA = \'dbo\' '
                       'AND TABLE_NAME = \'%s\')) '
                       'BEGIN '
                       'DELETE FROM [database].[dbo].[%s] '
                       'END' % (tableName,tableName)
session.execute(query)
print(query)
1

1 Answers

4
votes

The problem is you are not committing your transaction. Depending on your configuration, you will need to set autocommit to True, or commit your transaction after execution (typically handled in multiple transactions that would require a rollback):

You can set this here:

sessionmaker(bind=engine, autocommit=True)

or:

session.commit()

Reference to sessionmaker():

http://docs.sqlalchemy.org/en/latest/orm/session_api.html