-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmy_crud.java
More file actions
74 lines (54 loc) · 1.95 KB
/
my_crud.java
File metadata and controls
74 lines (54 loc) · 1.95 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
import java.sql.*;
import java.util.*;
public class my_crud {
public static void main(String[] args) {
String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
String DB_URL = "jdbc:mysql://localhost:3306/my_db";
String USER = "root";
String PASS = "";
try {
Class.forName(JDBC_DRIVER);
Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
String query = "CREATE TABLE IF NOT EXISTS users (id INT NOT NULL AUTO_INCREMENT, name VARCHAR(255), email VARCHAR(255), idn VARCHAR(255), PRIMARY KEY (id))";
stmt.executeUpdate(query);
Scanner scan = new Scanner(System.in);
System.out.println("1. Add User");
System.out.println("2. Read User");
System.out.print("Enter Choice: ");
String choice = scan.nextLine();
switch(choice) {
case "1":
//Add User
System.out.print("Enter user name: ");
String name = scan.nextLine();
System.out.print("Enter user email: ");
String email = scan.nextLine();
System.out.print("Enter identification number: ");
String idn = scan.nextLine();
query = "INSERT INTO users (name, email, idn) VALUES ('" + name + "', '" + email + "', '" + idn +"')";
stmt.executeUpdate(query);
break;
case "2":
System.out.print("Enter user id: ");
int id = scan.nextInt();
query = "SELECT * FROM users WHERE ID = " + id;
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
System.out.println("ID: " + rs.getInt("id"));
System.out.println("Name: " + rs.getString("name"));
System.out.println("Email: " + rs.getString("email"));
System.out.println("Indentification number: " + rs.getString("idn"));
} else {
System.out.println("User with id = " + id + " not found");
}
break;
}
scan.close();
stmt.close();
conn.close();
} catch(Exception e) {
System.out.print("Error: " + e.getMessage());
}
}
}