'Execute a file of sql and fetchall from each query to return as a Dataframe

Hello I have an sql file that contains a bunch of sql queries, mainly SELECT FROM TABLE types of query and some are CREATE TABLE or CREATE VIEW. Each query are separated by ;.

What I would like to do is to execute the file when fetch data from each of the SELECT FROM TABLE queries and append to a dataframe, and then this dataframe could be append to a dict.

This is my current file execution function:

def execute_file(self, file_path=None,commit=False):
        if file_path is None:
            print("File path must be passed")
        else:
            try:
                sql_file = open(file_path, 'r')
                self.cursor.execute(sql_file.read())
            except (Exception, Error) as e:
                self.connection.rollback()
                raise

            if commit:
                self.connection.commit()

Many thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source