SQL to text Learn programming Java

Lesson:

File Management


Exercise:

SQL to text


Objetive:

You must create a java 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


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();
	}
}

Juan A. Ripoll - Systems Tutorials and Programming Courses ©  All rights reserved.  Legal Conditions.