Search code examples
pythonsqlsql-serverpypyodbc

pypyodbc does not commit


I have a SQLServer TSQL query that has multiple INSERT statements that range from pretty basic to somewhat complex.

This query works in SQLServer Management Studio.

When I use Python pypyodbc package and run the script, the script runs but does not commit. I have tried with and without the commit() function.

BUT if I specify a SELECT statement at the end, the script commits the inserts.

So it's all good because it works, but I am putting an inapplicable SELECT statement at the end of all of my scripts.

Does anyone have any ideas how I can get these to commit without the SELECT statement at the end? I do not want to split the queries up into multiple queries.

Thank you!

    def execute_query(self,
                  query,
                  tuple_of_query_parameters,
                  commit=False,
                  return_insert_id=False,
                  return_results=True):
    self.open_cursor()

    try:
        self.connection_cursor.execute(query,
                                       tuple_of_query_parameters)

        result_set = None
        if return_results:
            if return_insert_id:
                result_set = self.connection_cursor.fetchone()[0]
            else:
                result_set = self.connection_cursor.fetchall()

            if commit:
                self.connection_cursor.commit()

    except pypyodbc.Error as e:
        print('Check for "USE" in script!!!')
        raise
    finally:
        self.close_cursor()

    return result_set

Solution

  • Try this:

    self.connection_cursor.execute(query,
                                       tuple_of_query_parameters)
    if commit:
        self.connection_cursor.commit() #put commit here, immediately after execute
    

    I think that will do the trick.