Advertisement
Guest User

Untitled

a guest
Oct 15th, 2017
79
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.62 KB | None | 0 0
  1.  
  2. import java.util.Scanner;
  3. import java.sql.*;
  4. import java.sql.Connection;
  5. import java.sql.DriverManager;
  6. import java.sql.ResultSet;
  7.  
  8. public class ListaaminenJaLisaaminen {
  9.  
  10. public static void main(String[] args) throws Exception {
  11. Scanner lukija = new Scanner(System.in);
  12. System.out.println("Tervetuloa!");
  13. while (true) {
  14. System.out.println("");
  15. System.out.println("Komennot:");
  16. System.out.println("1. Listaa kappaleet");
  17. System.out.println("2. Lisää kappale");
  18. System.out.println("3. Sulje");
  19.  
  20. String komento = lukija.nextLine();
  21.  
  22. if (komento.equals("3")) {
  23. break;
  24. }
  25.  
  26. if (komento.equals("1")) {
  27. listaa();
  28. }
  29.  
  30. if (komento.equals("2")) {
  31. lisaa();
  32. }
  33. }
  34. }
  35.  
  36. public static void listaa() throws SQLException {
  37. Connection connection = DriverManager.getConnection("jdbc:sqlite:db/levy.db");
  38.  
  39. PreparedStatement statement = connection.prepareStatement("SELECT * FROM Kappale");
  40. ResultSet resultSet = statement.executeQuery();
  41.  
  42. while (resultSet.next()) {
  43.  
  44. String nimi = resultSet.getString("nimi");
  45. String artisti = resultSet.getString("artisti");
  46. Integer levytysvuosi = resultSet.getInt("levytysvuosi");
  47. Integer pituus = resultSet.getInt("pituus");
  48.  
  49. System.out.println(artisti + ", " + nimi + " (" + pituus + " s), " + levytysvuosi);
  50. }
  51.  
  52. connection.close();
  53. }
  54.  
  55. public static void lisaa() throws SQLException {
  56. Scanner lukija = new Scanner(System.in);
  57.  
  58. System.out.print("Nimi: ");
  59. String uusiNimi = lukija.nextLine();
  60.  
  61. System.out.print("Artisti: ");
  62. String uusiArtisti = lukija.nextLine();
  63.  
  64. System.out.print("Levytysvuosi: :");
  65. int uusiVuosi = Integer.parseInt(lukija.nextLine());
  66.  
  67. System.out.print("Pituus: ");
  68. int uusiPituus = Integer.parseInt(lukija.nextLine());
  69.  
  70. Connection connection = DriverManager.getConnection("jdbc:sqlite:db/levy.db");
  71. PreparedStatement statement = connection.prepareStatement("INSERT INTO Kappale (nimi, artisti, levytysvuosi, pituus) VALUES (?, ?, ?, ?)");
  72. statement.setString(1, uusiNimi);
  73. statement.setString(2, uusiArtisti);
  74. statement.setInt(3, uusiVuosi);
  75. statement.setInt(4, uusiPituus);
  76. int changes = statement.executeUpdate();
  77.  
  78. statement.close();
  79.  
  80. connection.close();
  81.  
  82. }
  83.  
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement