SQL To Text - C# Programming Exercise

In this exercise, you need to create a C# program capable of parsing SQL INSERT commands and extracting their data into separate lines of text. The program should process an input file containing SQL commands, such as the following examples, and generate an output that shows the field values in a structured and separated manner. This exercise will allow you to work with string manipulation, file parsing, and SQL command processing.

 Category

File Management

 Exercise

SQL To Text

 Objective

You must create a C# program that is capable of parsing SQL INSERT commands and extracting 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

 Write Your C# Exercise

// Importing necessary namespaces
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

class SqlToText
{
    // Main method where the program execution begins
    static void Main()
    {
        // Path to the input SQL file
        string inputFilePath = "input.sql";

        // Path to the output text file where the result will be saved
        string outputFilePath = "output.txt";

        // Call the ParseSqlInsert method to process the SQL file and extract the data
        ParseSqlInsert(inputFilePath, outputFilePath);
    }

    // Method to parse the SQL INSERT statements and extract the data into a text format
    static void ParseSqlInsert(string inputFilePath, string outputFilePath)
    {
        try
        {
            // Read the entire SQL file
            string sqlContent = File.ReadAllText(inputFilePath);

            // Regex pattern to match INSERT INTO SQL statements
            string insertPattern = @"INSERT INTO\s+`?(\w+)`?\s?\((.*?)\)\s+VALUES\s?\((.*?)\);";

            // Match all the INSERT statements in the SQL content
            var matches = Regex.Matches(sqlContent, insertPattern, RegexOptions.IgnoreCase);

            // List to store the formatted output
            List outputLines = new List();

            foreach (Match match in matches)
            {
                // Get the table name
                string tableName = match.Groups[1].Value;

                // Get the field names as a comma-separated list
                string fieldNames = match.Groups[2].Value;

                // Get the values to be inserted
                string values = match.Groups[3].Value;

                // Split the field names and values by commas
                string[] fields = fieldNames.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                string[] valuesArray = values.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                // Clean up extra spaces or quotes around field names and values
                for (int i = 0; i < fields.Length; i++)
                {
                    fields[i] = fields[i].Trim().Trim('`').Trim();
                    valuesArray[i] = valuesArray[i].Trim().Trim('\'', '"').Trim();
                }

                // Add the table name to the output
                outputLines.Add($"Table: {tableName}\n");

                // Add each field and its corresponding value to the output
                for (int i = 0; i < fields.Length; i++)
                {
                    outputLines.Add($"{fields[i]}: {valuesArray[i]}");
                }

                // Add a blank line after each record
                outputLines.Add("");
            }

            // Write the result to the output file
            File.WriteAllLines(outputFilePath, outputLines);

            Console.WriteLine("SQL has been parsed and saved to the output file.");
        }
        catch (Exception ex)
        {
            // Catch any errors (e.g., file not found or read/write issues) and display an error message
            Console.WriteLine("Error: " + ex.Message);
        }
    }
}

 Share this C# exercise

 More C# Programming Exercises of File Management

Explore our set of C# programming exercises! Specifically designed for beginners, these exercises will help you develop a solid understanding of the basics of C#. 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 C#.

  •  PGM viewer

    The PGM format is one of the versions of the NetPBM image formats. Specifically, it is the variant capable of handling images in shades of gray. Its header starts with a line conta...

  •  Display BMP on console V2

    In this exercise, you are asked to develop a program in C# that can display a 72x24 BMP file on the console. To do this, you must use the information contained...

  •  Writing to a text file

    In this exercise of C#, you need to create a program that asks the user for several sentences (until they just press Enter without typing anything) and stores those s...

  •  Appending to a text file

    In this exercise of C#, you need to create a program that asks the user for several sentences (until they just press Enter without typing anything) and stores those s...

  •  Display file contents

    In this exercise of C#, you need to create a program that displays all the contents of a text file on the screen. The file name will either be entered via the command...

  •  Extended TextToHTML (files)

    In this exercise of C#, you need to expand the TextToHtml class so that it can dump its result to a text file. You should create a ToFile method that ta...