implement UserDao.java
This commit is contained in:
@@ -1,23 +1,63 @@
|
|||||||
package dev.dao;
|
package dev.dao;
|
||||||
|
|
||||||
|
import dev.database.DatabaseConnection;
|
||||||
import dev.model.User;
|
import dev.model.User;
|
||||||
|
|
||||||
|
import java.sql.Connection;
|
||||||
|
import java.sql.PreparedStatement;
|
||||||
|
import java.sql.ResultSet;
|
||||||
|
import java.sql.SQLException;
|
||||||
|
|
||||||
public class UserDao {
|
public class UserDao {
|
||||||
|
|
||||||
public boolean save(User user) {
|
public boolean save(User user) {
|
||||||
|
|
||||||
// TODO:
|
|
||||||
// Insert user into database
|
// Insert user into database
|
||||||
|
|
||||||
return false;
|
String sql = "INSERT INTO users (username, password, email) VALUES(?, ?, ?)";
|
||||||
|
|
||||||
|
try(Connection connection = DatabaseConnection.getConnection();
|
||||||
|
PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
|
||||||
|
|
||||||
|
preparedStatement.setString(1, user.getUsername());
|
||||||
|
preparedStatement.setString(2, user.getPassword());
|
||||||
|
preparedStatement.setString(3, user.getEmail());
|
||||||
|
|
||||||
|
return preparedStatement.executeUpdate() > 0;
|
||||||
|
|
||||||
|
} catch (SQLException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public User findByUsername(String username) {
|
public User findByUsername(String username) {
|
||||||
|
|
||||||
// TODO:
|
|
||||||
// Find a user by username
|
// Find a user by username
|
||||||
|
// Retrieve all orders of a user
|
||||||
|
String sql = "SELECT * FROM users WHERE username=?";
|
||||||
|
|
||||||
|
try (Connection connection = DatabaseConnection.getConnection();
|
||||||
|
PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
|
||||||
|
|
||||||
|
preparedStatement.setString(1, username);
|
||||||
|
|
||||||
|
ResultSet resultSet = preparedStatement.executeQuery();
|
||||||
|
|
||||||
|
if (resultSet.next()) {
|
||||||
|
|
||||||
|
User user = new User();
|
||||||
|
|
||||||
|
user.setId(resultSet.getInt("id"));
|
||||||
|
user.setUsername(resultSet.getString("username"));
|
||||||
|
user.setPassword(resultSet.getString("password"));
|
||||||
|
user.setEmail(resultSet.getString("email"));
|
||||||
|
|
||||||
|
return user;
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (SQLException e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
Reference in New Issue
Block a user