SQL to text Learn programming Java

Lesson:

File Management


Exercise:

SQL to text 42


Objetive:

You must create a java program capable of parsing SQL language INSERT commands and extracting their data to separate lines of text, as follows: if the input file contained 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:

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

persons name: juan Address: 5th Street, 6 age: 24

cities code: a name: alicante


Code:

package SQL2text;
import java.util.*;

public class Main
{
	public static void main(String[] args)
	{
		java.io.FileReader ficheroEntrada = null;
		String linea;
		String nombre;

		System.out.println("Not enough parameters!");
		System.out.print("Enter file name: ");
		nombre = new Scanner(System.in).nextLine();

		try
		{
			ficheroEntrada = new java.io.FileReader(nombre);
		}
		catch (RuntimeException e)
		{
			System.out.println(e.getMessage());
		}

		try
		{
			do
			{
				linea = ficheroEntrada.ReadLine();
				if (linea != null)
				{
					System.out.println();
					String tableName = linea.substring(12).split("[ ]", -1)[0];
					String[] campo = tangible.StringHelper.substring(linea, linea.indexOf("(") + 1, linea.indexOf(")") - linea.indexOf("(") - 1).split("[,]", -1);
					String[] valores = tangible.StringHelper.substring(linea, linea.indexOf("values (") + 9, linea.indexOf(");") - linea.indexOf("values (") - 9).split("[,]", -1);

					System.out.println(tableName);
					for (int i = 0; i < campo.length; i++)
					{
						System.out.print(campo[i].trim() + ": ");
						System.out.println(valores[i].trim().replace("'", ""));
					}
				}
			} while (linea != null);
		}
		catch (RuntimeException e)
		{
			System.out.println(e.getMessage());
		}
		new Scanner(System.in).nextLine();
	}
}