Skip to content

Commit

Permalink
Account DAO methods
Browse files Browse the repository at this point in the history
  • Loading branch information
jmsundin committed Jan 28, 2024
1 parent a405874 commit 1d7a644
Showing 1 changed file with 54 additions and 12 deletions.
66 changes: 54 additions & 12 deletions src/main/java/DAO/AccountDAO.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,30 +8,72 @@
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import java.util.List;
import java.util.ArrayList;

public class AccountDAO {

public Account insertAccount(Account account){
Connection connection = ConnectionUtil.getConnection();
public Account insertAccount(String username, String password){
try {
String sql = "INSERT INTO account (username, password) VALUES (?, ?)";
PreparedStatement ps = connection.prepareStatement(sql);
Connection conn = ConnectionUtil.getConnection();
String sql = "INSERT INTO account (username, password_) VALUES (?, ?)";
PreparedStatement ps = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);

//add code that leverages ps.setString here
ps.setString(1, account.getUsername());
ps.setString(2, account.getPassword());
ps.setString(1, username);
ps.setString(2, password);

ps.executeUpdate();
ResultSet pkeyResultSet = ps.getGeneratedKeys();
if (pkeyResultSet.next()){
int generated_account_id = (int) pkeyResultSet.getLong(1);
return new Account(generated_account_id, account.getUsername(), account.getPassword());
while (pkeyResultSet.next()) {
Account account = new Account(username, password);
account.setAccount_id((int) (pkeyResultSet.getLong(1)));
return account;
}
} catch(SQLException e){
e.printStackTrace();
}
return null;
}

public Account findAccountByUsername(String username) {
try {
Connection conn = ConnectionUtil.getConnection();
String sql = "SELECT account_id, username, password_ "
+ "FROM account WHERE username = ?";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, username);

}catch(SQLException e){
ResultSet rs = ps.executeQuery();
if (rs.next()) {
String usernameFromDB = rs.getString(2);
String password = rs.getString(3);
return new Account(usernameFromDB, password);
}
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}


public List<Account> getAllAccounts() {
List<Account> accounts = new ArrayList<>();
try {
Connection conn = ConnectionUtil.getConnection();
String sql = "SELECT * FROM account";
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String username = rs.getString(2);
String password = rs.getString(3);
Account account = new Account(username, password);
accounts.add(account);
System.out.println(account);
}
} catch (SQLException e) {
e.printStackTrace();
}
return accounts;
}
}

0 comments on commit 1d7a644

Please sign in to comment.