Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.FileNotFoundException;
- import java.io.IOException;
- import java.sql.*;
- import java.util.*;
- public class Main
- {
- public static void main(String[] args)
- {
- ArrayList<Autore> autori = new ArrayList();
- Scanner scan = new Scanner(System.in);
- HashMap<String, Libro> raccolta = new HashMap();
- try
- {
- Class.forName("com.mysql.jdbc.Driver");
- Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/authors","root","");
- Statement stmt = con.createStatement();
- ResultSet rs;
- PreparedStatement ps;
- // LETTURA
- String querySelect = "select * from Author";
- rs = stmt.executeQuery(querySelect);
- System.out.println("\n*** LISTA COMPLETA ***");
- while (rs.next())
- {
- Autore autore = new Autore(rs.getInt("id"), rs.getString("Nome"), rs.getString("Cognome"));
- autori.add(autore);
- }
- // STAMPA AUTORI
- for (Autore autore : autori)
- System.out.println(autore.toString());
- System.out.println("\n*** INSERIMENTO ***");
- if (!rs.next())
- {
- // INSERIMENTO LIBRI
- for (Autore autore : autori)
- {
- System.out.printf("%s", autore.toString());
- System.out.println("\nInserire un libro per quest'autore? [s/n]");
- char scelta = scan.nextLine().charAt(0);
- if (scelta == 's')
- {
- do
- {
- System.out.println("\nTitolo: ");
- String titolo = scan.nextLine();
- System.out.println("\nAnno pubblicazione: ");
- int pubblicazione = scan.nextInt();
- // INSERIMENTO NEL DB
- String queryInsert = "insert into Book (idAuthor, Titolo, Anno_pub) values (?, ?, ?)";
- ps = con.prepareStatement(queryInsert);
- ps.setInt(1, autore.getId());
- ps.setString(2, titolo);
- ps.setInt(3, pubblicazione);
- int n = ps.executeUpdate();
- System.out.printf("%d record inseriti", n);
- // INSERIMENTO HASHMAP
- raccolta.put(autore.getCognome(), new Libro(titolo, pubblicazione));
- System.out.println("\nInserire un altro libro? [s/n]");
- scan.skip("\\R?");
- scelta = scan.nextLine().charAt(0);
- }
- while (scelta == 's');
- }
- else if (scelta == 'n')
- {
- continue;
- }
- else
- {
- System.out.println("\nInput non valido.");
- break;
- }
- }
- }
- System.out.println("\nInserimento finito.");
- // STAMPA TOTALE
- System.out.println("\n***AUTORI - LIBRI***\n");
- for (String cognome : raccolta.keySet())
- {
- System.out.println("\n" + cognome + raccolta.get(cognome).toString() + "\n");
- }
- // SCRITTURA SU FILE
- FileManager filewr = new FileManager();
- filewr.scrivi(raccolta);
- }
- catch (SQLException e)
- {
- e.printStackTrace();
- }
- catch (ClassNotFoundException e)
- {
- e.printStackTrace();
- }
- catch (FileNotFoundException e)
- {
- e.printStackTrace();
- }
- catch (IOException e)
- {
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment