/*
* (c) FIT CVUT
*/
package cz.cvut.fit.tjv.tictactoe.db;
import cz.cvut.fit.tjv.tictactoe.player.Player;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Database class
*
* @author Filip Glazar
*/
public class Db {
private static Db instance = null;
private final Connection conn;
private final String url = "jdbc:derby://localhost:1527/tictactoe;user=app;password=app";
protected Db() throws SQLException {
conn = DriverManager.getConnection(url);
}
/**
* Return instance of database class
* @return Db
*/
public static Db getInstance() {
if(instance == null){
try {
instance = new Db();
} catch (SQLException ex) {
Logger.getLogger(Db.class.getName()).log(Level.SEVERE, null, ex);
}
}
return instance;
}
/**
* Inserts score of given player into table
* @param winner
*/
public void addScore(Player winner) {
try {
PreparedStatement ps = conn.prepareStatement("insert into app.result (player, score) valuees(?, ?)");
ps.setString(1, winner.getName());
ps.setInt(2, winner.getScore());
ps.execute();
ps.close();
} catch (SQLException ex) {
Logger.getLogger(Db.class.getName()).log(Level.SEVERE, null, ex);
}
}
/**
* Get aggregated score for given player name
* @param name
* @return score
*/
public int getScore(String name) {
int score = 0;
try {
PreparedStatement ps = conn.prepareStatement("select score from api.result where (player == ?)");
ps.setString(1, name);
ResultSet rs = ps.executeQuery();
ps.close();
while(rs.next()){
score += rs.getInt(1);
}
} catch (SQLException ex) {
Logger.getLogger(Db.class.getName()).log(Level.SEVERE, null, ex);
}
return score;
}
/**
* Return aggregated score for all players
* @return table
*/
public Map<String, Integer> getScoreTable() {
//TODO: implement
}
}