SQL to Plain Text - Python Programming Exercise

In this exercise, you will develop a Python program to parse SQL INSERT commands and extract their data into separate lines of text. This exercise is perfect for practicing file handling, string manipulation, and data extraction in Python. By implementing this program, you will gain hands-on experience in handling file operations, string manipulation, and data extraction in Python. This exercise not only reinforces your understanding of file handling but also helps you develop efficient coding practices for managing user interactions.

 Category

Managing Files

 Exercise

SQL To Plain Text

 Objective

Develop a Python program to parse SQL INSERT commands and extract their data into separate lines of text, as follows. If the input file contains these three lines:

INSERT INTO people (name, address, age) VALUES ("smith, pedro", "your street", 23);

INSERT INTO people (name, address, age) VALUES ("juan", "calle cinco, 6", 24);

INSERT INTO cities (code, name) VALUES ("a", "alicante");

The resulting file should have on each line the name of a field, followed by a colon and its value. In addition, each record must be preceded by the name of the table and followed by a blank line, like this:

Table: people

name: smith, pedro address: your street age: 23

Table: people

name: juan address: calle cinco, 6 age: 24

Table: cities

code: a name: alicante

 Example Python Exercise

 Copy Python Code
# Python program to parse SQL INSERT commands and extract data

import re

def parse_sql_insert(input_file, output_file):
    """
    Parses SQL INSERT commands from an input file and writes the extracted data to an output file.
    """
    try:
        with open(input_file, 'r', encoding='utf-8') as infile, open(output_file, 'w', encoding='utf-8') as outfile:
            for line in infile:
                # Match the INSERT INTO statement
                match = re.match(r"INSERT INTO (\w+) \((.+?)\) VALUES \((.+?)\);", line.strip())
                if match:
                    table_name = match.group(1)  # Extract table name
                    fields = match.group(2).split(", ")  # Extract field names
                    values = match.group(3).split(", ")  # Extract values
                    
                    # Clean up values (removing quotes)
                    values = [value.strip('"') for value in values]
                    
                    # Write the table name
                    outfile.write(f"Table: {table_name}\n\n")
                    
                    # Write the fields and their corresponding values
                    for field, value in zip(fields, values):
                        outfile.write(f"{field}: {value}\n")
                    
                    outfile.write("\n")  # Blank line between records
        print(f"Extracted data written to '{output_file}'.")
    except FileNotFoundError:
        print(f"Error: The input file '{input_file}' was not found.")
    except Exception as e:
        print(f"Error: {str(e)}")


# Example usage
if __name__ == "__main__":
    # File paths
    input_file = "insert_commands.sql"       # Input file containing SQL INSERT commands
    output_file = "parsed_output.txt"        # Output file for extracted data

    parse_sql_insert(input_file, output_file)

 Output

Input (insert_commands.sql):

INSERT INTO people (name, address, age) VALUES ("smith, pedro", "your street", 23);
INSERT INTO people (name, address, age) VALUES ("juan", "calle cinco, 6", 24);
INSERT INTO cities (code, name) VALUES ("a", "alicante");

Output (parsed_output.txt):

Table: people

name: smith, pedro
address: your street
age: 23

Table: people

name: juan
address: calle cinco, 6
age: 24

Table: cities

code: a
name: alicante

 Share this Python Exercise

 More Python Programming Exercises of Managing Files

Explore our set of Python Programming Exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of Python. From variables and data types to control structures and simple functions, each exercise is crafted to challenge you incrementally as you build confidence in coding in Python.

  •  PGM Image Viewer

    In this exercise, you will develop a Python program to create a utility that reads and displays images in the PGM format, which is a version of the NetPBM image forma...

  •  Console BMP Viewer V2

    In this exercise, you will develop a Python program to create a utility that displays a 72x24 BMP file on the console. This exercise is perfect for practicing ...

  •  Saving Data to a Text File

    In this exercise, you will develop a Python program to collect multiple sentences from the user (continuing until the user presses Enter without typing anything) and ...

  •  Adding Content to a Text File

    In this exercise, you will develop a Python program that prompts the user to input multiple sentences, stopping when they press Enter without typing anything. This ...

  •  Show File Data

    In this exercise, you will develop a Python program to read and display the contents of a text file. This exercise is perfect for practicing file handling, com...

  •  TextToHTML with File Integration

    In this exercise, you will develop a Python program to enhance the TextToHTML class by adding the ability to save its results into a text file. This exercise i...