· 7 years ago · Dec 04, 2018, 08:36 PM
1import java.sql.*;
2import java.util.Scanner;
3
4class MyClass {
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://localhost: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 Scanner in = new Scanner(System.in);
20
21 while (true) {
22 System.out.println("\n--------------Add new car press 1, for display cars press 2--------------\n");
23 String userChoice = in.nextLine();
24
25 if (userChoice.equals("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:\n");
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 System.out.println("Car successfully added to database\n");
38 }
39 else if (userChoice.equals("2")) {
40 statement = connection.createStatement();
41 String selectQuery = "SELECT * FROM cars";
42 ResultSet response = statement.executeQuery(selectQuery);
43 int i = 1;
44 System.out.print("Nr\t");
45 System.out.print("Brand\t");
46 System.out.print("Model\t");
47 System.out.print("Color\n");
48
49 while (response.next()) {
50 System.out.print(i + "\t");
51 System.out.print(response.getString("brand") + "\t");
52 System.out.print(response.getString("model") + "\t");
53 System.out.print(response.getString("color") + "\n");
54 i++;
55 }
56 }
57 }
58 } catch (Exception e) {
59 System.out.println(e);
60 }
61 }
62}