/*
** Demonstrates a PreparedStatement and handling SQL injection.
*/
import java.sql.*;
import java.util.Scanner;

public class DBDemo8
{
	public static void main(String args[])
		throws ClassNotFoundException,SQLException
	{
		Scanner kb= new Scanner(System.in);
		String artistName;
		String database="demo_db";
		String url="jdbc:postgresql://csci.hsutx.edu/"+database;
		String username="demo";
		String password="welovethisclass";
		Connection con;
		PreparedStatement pstmt;
		Statement stmt;
		ResultSet result;

		Class.forName("org.postgresql.Driver");	 // load the driver
		System.out.print("Driver Loaded Successfully!\n");
		con= DriverManager.getConnection(url,username,password);
		System.out.print("Connection to database'"+database+"' established.\n");

		stmt= con.createStatement();
		stmt.executeUpdate("set search_path to albumdb");

		System.out.print("Enter name of artist: ");
		artistName= kb.nextLine();
		stmt.executeUpdate("INSERT INTO artist (id,name,hometown) VALUES(default,'"+artistName+"','Abilene, TX')");
		//pstmt= con.prepareStatement("INSERT INTO artist (id,name,hometown) VALUES(default,?,'Abilene, TX')");
		//pstmt= con.prepareStatement("INSERT INTO artist (id,name,hometown) VALUES(default,'"+artistName+"','Abilene, TX')");
		//pstmt.setString(1,artistName);
		//pstmt.executeUpdate();

		result= stmt.executeQuery("select * from artist");
		while (result.next()) {
			System.out.println(result.getString("id"));	 // field name notation
			System.out.println(result.getString("name"));
			System.out.println(result.getString(3));			// positional notation
			System.out.println();
		}
		con.close();	// close connection to username
	}
}
