Advertisement
Guest User

Untitled

a guest
Dec 4th, 2018
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.28 KB | None | 0 0
  1. import java.sql.*;
  2. import java.util.Scanner;
  3.  
  4. class MyClass {
  5.     public static void main(String args[]) {
  6.  
  7.         Statement statement;
  8.         Connection connection = null;
  9.  
  10.         try {
  11.  
  12.             Class.forName("com.mysql.jdbc.Driver");
  13.             connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDB", "mbobel", "password");
  14.  
  15.             String createTable = "CREATE TABLE IF NOT EXISTS cars (brand VARCHAR(20), model VARCHAR(20), color VARCHAR(20))";
  16.  
  17.             statement = connection.createStatement();
  18.             statement.executeUpdate(createTable);
  19.  
  20.             Scanner in = new Scanner(System.in);
  21.             while(true) {
  22.                 System.out.println("MENU\n If you want add new car press 1\nIf you want display cars press 2\n");
  23.                 String userChoice = in.nextLine();
  24.                
  25.                 if (userChoice == "1") {
  26.                         System.out.print("Type car brand:\n");
  27.                         String brand = in.nextLine();
  28.                         System.out.print("Type car model:\n");
  29.                         String model = in.nextLine();
  30.                         System.out.print("Type car color");
  31.                         String color = in.nextLine();
  32.  
  33.                         statement = connection.createStatement();
  34.  
  35.                         String insertQuery = "INSERT INTO cars VALUES('" + brand + "', '" + model +"', '" + color + "')";
  36.                         statement.executeUpdate(insertQuery);
  37.                     }
  38.                 }
  39.                 if (userChoice == "2") {
  40.                     statement = connection.createStatement();
  41.                     String selectQuery = "SELECT * FROM cars";
  42.                     ResultSet response = statement.executeQuery(selectQuery );
  43.                     int i = 0;
  44.  
  45.                     while (response.next()) {
  46.                         System.out.print(i + "\t");
  47.                         System.out.print(response.getString("brand") + "\t");
  48.                         System.out.print(response.getString("model") + "\t");
  49.                         System.out.print(response.getString("color") + "\n");
  50.                         i++;
  51.                 }
  52.             }
  53.         } catch(Exception e) {
  54.             System.out.println(e);
  55.         }
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement