· 8 years ago · Nov 22, 2017, 12:30 AM
1package OrdersDataBase;
2
3import java.sql.Connection;
4import java.sql.PreparedStatement;
5import java.sql.ResultSet;
6import java.util.ArrayList;
7import java.util.List;
8
9/**
10 * Hello world!
11 *
12 */
13import java.sql.*;
14import java.util.Random;
15import java.util.Scanner;
16
17public class Clients {
18 static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/mydb";
19 static final String DB_USER = "root";
20 static final String DB_PASSWORD = "1111";
21
22 static Connection conn;
23
24 public static void main(String[] args) {
25 Scanner sc = new Scanner(System.in);
26 try {
27 try {
28 // create connection
29 conn = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
30 initDB();
31
32 while (true) {
33 System.out.println("1: add client");
34
35 System.out.print("-> ");
36
37 String s = sc.nextLine();
38 switch (s) {
39 case "1":
40 addOrder(sc);
41 break;
42
43 default:
44 return;
45 }
46 }
47 } finally {
48 sc.close();
49 if (conn != null) conn.close();
50 }
51 } catch (SQLException ex) {
52 ex.printStackTrace();
53 return;
54 }
55 }
56
57 private static void initDB() throws SQLException {
58 Statement st = conn.createStatement();
59 try {
60 st.execute("DROP TABLE IF EXISTS Clients");
61 st.execute("CREATE TABLE Clients (id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, name VARCHAR(20) NOT NULL, age INT)");
62 } finally {
63 st.close();
64 }
65 }
66
67 private static void addOrder(Scanner sc) throws SQLException {
68 System.out.print("Enter Client: ");
69 String name = sc.nextLine();
70 System.out.print("Enter age: ");
71 String sAge = sc.nextLine();
72 int age = Integer.parseInt(sAge);
73
74 PreparedStatement ps = conn.prepareStatement("INSERT INTO Clients (name, age) VALUES(?, ?)");
75 try {
76 ps.setString(1, name);
77 ps.setInt(2, age);
78 ps.executeUpdate(); // for INSERT, UPDATE & DELETE
79 } finally {
80 ps.close();
81 }
82
83
84
85 ps = conn.prepareStatement("UPDATE Clients SET age = ? WHERE name = ?");
86 try {
87 ps.setInt(1, age);
88 ps.setString(2, name);
89 ps.executeUpdate(); // for INSERT, UPDATE & DELETE
90 } finally {
91 ps.close();
92 }
93 }
94
95
96
97
98}