Untitled

 avatar
unknown
plain_text
a month ago
1.6 kB
6
Indexable
def read_and_modify_sql(sql_file, schema_name):
    """Read SQL file and replace the schema name"""
    try:
        with open(sql_file, 'r') as file:
            sql_content = file.read()
            
        # Replace the hardcoded schema with the provided schema
        modified_sql = sql_content.replace("dcc.owner in ('RMS')", f"dcc.owner in ('{schema_name}')")
        
        return modified_sql
    except Exception as e:
        printf(f'Error reading/modifying SQL file: {e}')
        return None

def execute_sql_to_csv(connection, sql_query, output_csv):
    """Execute SQL query and save results to CSV"""
    try:
        cursor = connection.cursor()
        cursor.execute(sql_query)
        
        # Get column names from cursor description
        columns = [col[0] for col in cursor.description]
        
        # Write to CSV
        with open(output_csv, 'w', newline='') as csvfile:
            from csv import writer
            csv_writer = writer(csvfile)
            
            # Write header
            csv_writer.writerow(columns)
            
            # Write data rows
            for row in cursor:
                # Convert None to empty string and all other values to string
                csv_row = ['' if val is None else str(val) for val in row]
                csv_writer.writerow(csv_row)
        
        cursor.close()
        printf(f'Successfully created CSV file: {output_csv}')
        return True
    except Exception as e:
        printf(f'Error executing SQL and creating CSV: {e}')
        if 'cursor' in locals():
            cursor.close()
        return False
Leave a Comment