-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathDataManager.java
More file actions
129 lines (112 loc) · 4.76 KB
/
Copy pathDataManager.java
File metadata and controls
129 lines (112 loc) · 4.76 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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import java.sql.*;
public class DataManager {
// Database connection details
private static final String DB_URL = "jdbc:mysql://localhost:3306/snake_game_db";
private static final String DB_USER = "root";
private static final String DB_PASSWORD = "Jhotika@####";
private Connection conn; // JDBC connection object
// Constructor: Establishes connection and initializes the database schema
public DataManager() {
try {
// Connect to MySQL database
conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
System.out.println("Database connected successfully.");
// Create necessary tables if they don't already exist
createTables();
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Database connection failed.");
}
}
// Creates Players and Scores tables with appropriate constraints
private void createTables() throws SQLException {
Statement stmt = conn.createStatement();
// SQL to create the Players table
stmt.executeUpdate("""
CREATE TABLE IF NOT EXISTS Players (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) UNIQUE NOT NULL
)
""");
// SQL to create the Scores table with a foreign key reference to Players
stmt.executeUpdate("""
CREATE TABLE IF NOT EXISTS Scores (
id INT AUTO_INCREMENT PRIMARY KEY,
player_id INT NOT NULL,
score INT NOT NULL,
FOREIGN KEY (player_id) REFERENCES Players(id)
)
""");
}
// Retrieves a player's ID by name, or creates a new record if player doesn't exist
public int getOrCreatePlayerId(String playerName) {
try {
// Try to find the player by name
PreparedStatement select = conn.prepareStatement(
"SELECT id FROM Players WHERE name = ?");
select.setString(1, playerName);
ResultSet rs = select.executeQuery();
if (rs.next()) {
// If player exists, return the ID
return rs.getInt("id");
} else {
// Player doesn't exist — insert a new player record
PreparedStatement insert = conn.prepareStatement(
"INSERT INTO Players (name) VALUES (?)", Statement.RETURN_GENERATED_KEYS);
insert.setString(1, playerName);
insert.executeUpdate();
// Retrieve the auto-generated ID of the new player
ResultSet keys = insert.getGeneratedKeys();
if (keys.next()) {
return keys.getInt(1);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return -1; // Return -1 if something failed
}
// Inserts a player's score into the Scores table
public void saveScore(int playerId, int score) {
try {
// Prepare an INSERT statement for Scores table
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO Scores (player_id, score) VALUES (?, ?)");
ps.setInt(1, playerId); // Set the player ID
ps.setInt(2, score); // Set the score
ps.executeUpdate(); // Execute the INSERT
System.out.println("Score saved successfully.");
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Failed to save score.");
}
}
// Fetches the highest score of a specific player
public int getHighScore(int playerId) {
try {
// Prepare a query to get the MAX score for a player
PreparedStatement ps = conn.prepareStatement(
"SELECT MAX(score) AS high_score FROM Scores WHERE player_id = ?");
ps.setInt(1, playerId); // Bind the player ID
ResultSet rs = ps.executeQuery();
if (rs.next()) {
return rs.getInt("high_score"); // Return the highest score
}
} catch (SQLException e) {
e.printStackTrace();
}
return 0; // If player has no scores or error occurs, return 0
}
// Closes the database connection safely
public void closeConnection() {
try {
if (conn != null) {
conn.close();
System.out.println("Database connection closed.");
}
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Failed to close the database connection.");
}
}
}