-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserDAO.java
More file actions
65 lines (60 loc) · 2.38 KB
/
UserDAO.java
File metadata and controls
65 lines (60 loc) · 2.38 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
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDAO {
public boolean registerUser(User user) {
try (Connection conn = DBConnection.getConnection()) {
String query = "INSERT INTO users (username, password, email) VALUES (?, ?, ?)";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, user.getUsername());
stmt.setString(2, user.getPassword());
stmt.setString(3, user.getEmail());
return stmt.executeUpdate() > 0;
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public User loginUser(String email, String password) {
try (Connection conn = DBConnection.getConnection()) {
String query = "SELECT * FROM users WHERE email = ? AND password = ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, email);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
if (rs.next()) {
User user = new User();
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("username"));
user.setEmail(rs.getString("email"));
return user;
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public boolean usernameExists(String username) {
try (Connection conn = DBConnection.getConnection()) {
String query = "SELECT * FROM users WHERE username = ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, username);
return stmt.executeQuery().next();
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public boolean emailExists(String email) {
try (Connection conn = DBConnection.getConnection()) {
String query = "SELECT * FROM users WHERE email = ?";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.setString(1, email);
return stmt.executeQuery().next();
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}