-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserDAO.java
More file actions
100 lines (76 loc) · 3.05 KB
/
UserDAO.java
File metadata and controls
100 lines (76 loc) · 3.05 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
import java.sql.*;
public class UserDAO {
// 🔹 REGISTER USER
public String registerUser(String name, String email, String accNo, String password) {
// ✅ Validate Account Number
if (accNo == null || accNo.length() != 11 || !accNo.matches("\\d+")) {
return "Account number must be exactly 11 digits!";
}
// ✅ Validate Name
if (name == null || name.trim().isEmpty()) {
return "Name cannot be empty!";
}
// ✅ Validate Password
if (password == null || password.length() < 4) {
return "Password must be at least 4 characters!";
}
try {
Connection con = DBConnection.getConnection();
if (con == null) {
return "Database connection failed!";
}
// 🔍 Check if account already exists
String checkQuery = "SELECT * FROM users WHERE account_no=?";
PreparedStatement checkPs = con.prepareStatement(checkQuery);
checkPs.setString(1, accNo);
ResultSet rs = checkPs.executeQuery();
if (rs.next()) {
return "Account already exists!";
}
// 📝 Insert New User
String insertQuery = "INSERT INTO users(name, account_no, password,email) VALUES (?, ?, ?, ?)";
PreparedStatement ps = con.prepareStatement(insertQuery);
ps.setString(1, name);
ps.setString(2, accNo);
ps.setString(3, password);
ps.setString(4, email);
int result = ps.executeUpdate();
if (result > 0) {
return "SUCCESS";
} else {
return "Registration failed!";
}
} catch (SQLException e) {
return "Database Error: " + e.getMessage();
} catch (Exception e) {
return "Error: " + e.getMessage();
}
}
// 🔹 LOGIN VALIDATION
public String validateLogin(String accNo, String password) {
// ✅ Basic Validation
if (accNo == null || accNo.isEmpty() || password == null || password.isEmpty()) {
return "Please enter all fields!";
}
try {
Connection con = DBConnection.getConnection();
if (con == null) {
return "Database connection failed!";
}
String query = "SELECT * FROM users WHERE account_no=? AND password=?";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, accNo);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return "SUCCESS";
} else {
return "Invalid Account Number or Password!";
}
} catch (SQLException e) {
return "Database Error: " + e.getMessage();
} catch (Exception e) {
return "Error: " + e.getMessage();
}
}
}