Advertisement
Guest User

Untitled

a guest
Dec 6th, 2018
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.98 KB | None | 0 0
  1. import java.sql.*;
  2. import java.util.Scanner;
  3.  
  4. class MySql {
  5. public static void main(String args[]) {
  6.  
  7. Statement statement;
  8. Connection connection = null;
  9.  
  10. try {
  11. Class.forName("com.mysql.cj.jdbc.Driver");
  12. connection = DriverManager.getConnection("jdbc:mysql://pwcho2018-83723:3306/myDB", "mbobel", "password");
  13.  
  14. String createTable = "CREATE TABLE IF NOT EXISTS cars (brand VARCHAR(20), model VARCHAR(20), color VARCHAR(20))";
  15.  
  16. statement = connection.createStatement();
  17. statement.executeUpdate(createTable);
  18.  
  19. String insertQuery1 = "INSERT INTO cars VALUES('Seat', 'Leon','Red)";
  20. statement.executeUpdate(insertQuery1);
  21.  
  22. String insertQuery2 = "INSERT INTO cars VALUES('Fiat', 'Multipla','Black')";
  23. statement.executeUpdate(insertQuery2);
  24.  
  25. String insertQuery3 = "INSERT INTO cars VALUES('Ford', 'Fiesta','Green')";
  26. statement.executeUpdate(insertQuery3);
  27.  
  28. Scanner in = new Scanner(System.in);
  29.  
  30. while (true) {
  31. System.out.println("\n--------------Add new car press 1, for display cars press 2--------------\n");
  32. String userChoice = in.nextLine();
  33.  
  34. if (userChoice.equals("1")) {
  35. System.out.print("Type car brand:\n");
  36. String brand = in.nextLine();
  37. System.out.print("Type car model:\n");
  38. String model = in.nextLine();
  39. System.out.print("Type car color:\n");
  40. String color = in.nextLine();
  41.  
  42. statement = connection.createStatement();
  43.  
  44. String insertQuery = "INSERT INTO cars VALUES('" + brand + "', '" + model + "', '" + color + "')";
  45. statement.executeUpdate(insertQuery);
  46. System.out.println("Car successfully added to database\n");
  47. }
  48. else if (userChoice.equals("2")) {
  49. statement = connection.createStatement();
  50. String selectQuery = "SELECT * FROM cars";
  51. ResultSet response = statement.executeQuery(selectQuery);
  52. int i = 1;
  53. System.out.print("Nr\t");
  54. System.out.print("Brand\t");
  55. System.out.print("Model\t");
  56. System.out.print("Color\n");
  57.  
  58. while (response.next()) {
  59. System.out.print(i + "\t");
  60. System.out.print(response.getString("brand") + "\t");
  61. System.out.print(response.getString("model") + "\t");
  62. System.out.print(response.getString("color") + "\n");
  63. i++;
  64. }
  65. }
  66. }
  67. } catch (Exception e) {
  68. System.out.println(e);
  69. }
  70. }
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement