Advertisement
Guest User

Untitled

a guest
Nov 24th, 2017
233
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 9.95 KB | None | 0 0
  1. Code listing 11.1 TeamDB.java
  2. import java.util.Scanner;
  3. import java.sql.*;
  4. /**
  5. This program uses a database to keep track of summer T-ball
  6. teams, games, and season records.
  7. */
  8. public class TeamDB
  9. {
  10. public static void main(String[] args)
  11. {
  12. // Create a named constant for the URL
  13. // NOTE: This value is specific for Java DB
  14. final String DB_URL = "jdbc:derby:TeamDB;create=true";
  15. Connection conn;
  16. try
  17. {
  18. // Create a connection to the database
  19. conn = DriverManager.getConnection(DB_URL);
  20. char choice;
  21. Scanner keyboard = new Scanner(System.in);
  22. System.out.println("Welcome to the Sports " +
  23. "Teams Database Manager!");
  24. do
  25. {
  26. printMenu();
  27. choice = keyboard.nextLine().charAt(0);
  28. switch(choice)
  29. {
  30. case '0':
  31. // Close the connection
  32. conn.close();
  33. break;
  34. case '1':
  35. viewTeams(conn);
  36. break;
  37. case '2':
  38. viewSchedule(conn);
  39. break;
  40. case '3':
  41. addTeams(conn);
  42. break;
  43. case '4':
  44. addGames(conn);
  45. break;
  46. case '5':
  47. enterScores(conn);
  48. break;
  49. case '6':
  50. beginNewSeason(conn);
  51. break;
  52. }
  53. } while(choice != '0');
  54. }
  55. catch(Exception ex)
  56. {
  57. System.out.println("ERROR: " + ex.getMessage());
  58. }
  59. }
  60. /**
  61. The printMenu method displays the menu choices
  62. for the user to work with the database.
  63. */
  64. public static void printMenu()
  65. {
  66. System.out.println();
  67. System.out.println("Select from the following options:");
  68. System.out.println("1. View team standings");
  69. System.out.println("2. View the schedule");
  70. System.out.println("3. Add a team");
  71. System.out.println("4. Add a game to the schedule");
  72. System.out.println("5. Enter game scores");
  73. System.out.println("6. Begin a new season");
  74. System.out.println("0. Exit the program");
  75. }
  76. /**
  77. The beginNewSeason method is a utility method that
  78. removes the tables and allows the user to reset the
  79. database for a new season.
  80. @param conn A connection to the database.
  81. */
  82. public static void beginNewSeason(Connection conn)
  83. {
  84. try
  85. {
  86. Statement stmt = conn.createStatement();
  87. // Remove tables if database tables have been created.
  88. // This will throw an exception if the tables do not exist
  89. stmt.execute("DROP TABLE Games");
  90. stmt.execute("DROP TABLE Teams");
  91. // Once the tables have been removed, call the method to
  92. // create and initialize the tables
  93. System.out.println("Reinitializing database " +
  94. "for a new season");
  95. createTeamDB(conn);
  96. }
  97. catch(Exception ex)
  98. {
  99. // Call the method to create tables for the database
  100. System.out.println("Creating database for the first time");
  101. createTeamDB(conn);
  102. }
  103. }
  104. /**
  105. The createTeamDB method is a utility method that
  106. creates the tables and initializes the database
  107. with teams and games.
  108. @param conn A connection to the database.
  109. */
  110. public static void createTeamDB(Connection conn)
  111. {
  112. try
  113. {
  114. Statement stmt = conn.createStatement();
  115. // Create the table of teams
  116. stmt.execute("CREATE TABLE Teams (" +
  117. "TeamName CHAR(15) NOT NULL PRIMARY KEY, " +
  118. "Wins INT, " + "Losses INT, " +
  119. "Ties INT" + ")");
  120. // Add some teams
  121. stmt.executeUpdate("INSERT INTO Teams " +
  122. "(TeamName) " +
  123. "VALUES ('Astros')");
  124. stmt.executeUpdate("INSERT INTO Teams " +
  125. "(TeamName) " +
  126. "VALUES ('Marlins')");
  127. stmt.executeUpdate("INSERT INTO Teams " +
  128. "(TeamName) " +
  129. "VALUES ('Brewers')");
  130. stmt.executeUpdate("INSERT INTO Teams " +
  131. "(TeamName) " +
  132. "VALUES ('Cubs')");
  133. // Create a listing of the games to be played
  134. stmt.execute("CREATE TABLE Games (" +
  135. "GameNumber INT NOT NULL PRIMARY KEY, " +
  136. "HomeTeam CHAR(15) NOT NULL REFERENCES " +
  137. "Teams (TeamName), " +
  138. "HomeTeamScore INT, " +
  139. "VisitorTeam CHAR(15) NOT NULL " +
  140. "REFERENCES Teams (TeamName), " +
  141. "VisitorTeamScore INT" + ")");
  142. stmt.executeUpdate("INSERT INTO Games " +
  143. "(GameNumber, HomeTeam, VisitorTeam) " +
  144. "VALUES (1, 'Astros', 'Brewers')");
  145. stmt.executeUpdate("INSERT INTO Games " +
  146. "(GameNumber, HomeTeam, VisitorTeam) " +
  147. "VALUES (2, 'Brewers', 'Cubs')");
  148. stmt.executeUpdate("INSERT INTO Games " +
  149. "(GameNumber, HomeTeam, VisitorTeam) " +
  150. "VALUES (3, 'Cubs', 'Astros')");
  151. }
  152. catch (Exception ex)
  153. {
  154. System.out.println("ERROR: " + ex.getMessage());
  155. }
  156. }
  157. /**
  158. The addTeams method allows the user to add
  159. more teams to the database.
  160. @param conn A connection to the database.
  161. */
  162. public static void addTeams(Connection conn)
  163. {
  164. Scanner keyboard = new Scanner(System.in);
  165. try
  166. {
  167. char ans;
  168. String teamName;
  169. Statement stmt = conn.createStatement();
  170. do
  171. {
  172. // TASK #3
  173. // Prompt the user for a new team name
  174. // Write SQL statement and update the Teams table
  175. System.out.print("Do you want to enter another team: ");
  176. ans = keyboard.nextLine().charAt(0);
  177. } while(ans == 'Y'|| ans == 'y');
  178. }
  179. catch(Exception ex)
  180. {
  181. System.out.println("ERROR: " + ex.getMessage());
  182. }
  183. }
  184. /**
  185. The addGames method allows the user to add games to the
  186. schedule. A unique game number is created for each game
  187. on the schedule.The user will need to supply a home team
  188. name and a visitor team name from the keyboard.
  189. @param conn A connection to the database.
  190. */
  191. public static void addGames(Connection conn)
  192. {
  193. Scanner keyboard = new Scanner (System.in);
  194. try
  195. {
  196. char ans;
  197. String homeTeam;
  198. String visitingTeam;
  199. int gameNumber = 1;
  200. Statement stmt = conn.createStatement();
  201. // This retrieves the data and allows you to count
  202. // the number of games already scheduled so that you
  203. // add a unique game number
  204. String sqlStatement = "SELECT * from Games";
  205. ResultSet result = stmt.executeQuery(sqlStatement);
  206. while(result.next())
  207. {
  208. gameNumber++;
  209. }
  210. do
  211. {
  212. System.out.print("Enter the home team name: ");
  213. homeTeam = keyboard.nextLine();
  214. System.out.print("Enter the visiting team name: ");
  215. visitingTeam = keyboard.nextLine();
  216. sqlStatement = "INSERT INTO Games " +
  217. "(GameNumber, HomeTeam, VisitorTeam) " +
  218. "VALUES (" + gameNumber + ", '" +
  219. homeTeam + "', '" + visitingTeam + "')";
  220. stmt.executeUpdate(sqlStatement);
  221. System.out.print("Do you want to enter another game: ");
  222. ans = keyboard.nextLine().charAt(0);
  223. } while(ans == 'Y'|| ans == 'y');
  224. }
  225. catch(Exception ex)
  226. {
  227. System.out.println("ERROR: " + ex.getMessage());
  228. }
  229. }
  230. /**
  231. The viewTeams method displays a table listing the
  232. team names and season records. Since teams have not
  233. yet played, all numbers are zero.
  234. @param conn A connection to the database.
  235. */
  236. public static void viewTeams(Connection conn)
  237. {
  238. try
  239. {
  240. // Create a Statement object
  241. Statement stmt = conn.createStatement();
  242. // Create a string with a SELECT statement
  243. String sqlStatement = "SELECT * FROM Teams";
  244. // Send the statement to the DBMS
  245. ResultSet result = stmt.executeQuery(sqlStatement);
  246. System.out.printf("%-15s %10s %10s %10s\n",
  247. "Team Name", "Win", "Lose",
  248. "Tie");
  249. // Display the contents of the result set
  250. // The result set will have 5 columns
  251. while(result.next())
  252. {
  253. System.out.printf("%-15s %10d %10d %10d\n",
  254. result.getString("TeamName"),
  255. result.getInt("Wins"),
  256. result.getInt("Losses"),
  257. result.getInt("Ties"));
  258. }
  259. }
  260. catch(Exception ex)
  261. {
  262. System.out.println("ERROR: " + ex.getMessage());
  263. }
  264. }
  265. /**
  266. The viewSchedule method retrieves and displays the
  267. teams and scores for all games.
  268. @param conn A connection to the database.
  269. */
  270. public static void viewSchedule(Connection conn)
  271. {
  272. try
  273. {
  274. // Create a Statement object
  275. Statement stmt = conn.createStatement();
  276. // TASK #2
  277. // Create a string with a SELECT statement
  278. // Send the statement to the DBMS
  279. // This is a suggested column headings display
  280. System.out.println("List of games and scores:");
  281. System.out.printf("%-6s %-20s %6s %-20s %6s\n",
  282. "GameID", "Home", "Score",
  283. "Visitor", "Score");
  284. // TASK #2
  285. // Use a while loop to display the result set
  286. // The result set will have five columns
  287. }
  288. catch(Exception ex)
  289. {
  290. System.out.println("ERROR: " + ex.getMessage());
  291. }
  292. }
  293. /**
  294. The enterScores method allows user to enter scores for both
  295. teams. The method will update the Games table with the scores
  296. entered. It will also compare the scores to determine the
  297. winning and losing teams (or tie) and update the appropriate
  298. column in the Teams table for each team involved in the game.
  299. @param conn A connection to the database.
  300. */
  301. public static void enterScores(Connection conn)
  302. {
  303. Scanner keyboard = new Scanner(System.in);
  304. try
  305. {
  306. char ans;
  307. int gameNumber;
  308. String homeTeam;
  309. String visitingTeam;
  310. int score1;
  311. int score2;
  312. String sqlStatement;
  313. ResultSet result;
  314. Statement stmt = conn.createStatement();
  315. do
  316. {
  317. viewSchedule(conn);
  318. System.out.print("Enter the game ID: ");
  319. gameNumber = keyboard.nextInt();
  320. // TASK #4
  321. // Get the result set from a query that selects all
  322. // information for the gameNumber the user entered
  323. if(result.next())
  324. {
  325. homeTeam = result.getString("HomeTeam");
  326. visitingTeam = result.getString("VisitorTeam");
  327. System.out.print("Enter the score for the " +
  328. homeTeam);
  329. score1 = keyboard.nextInt();
  330. System.out.print("Enter the score for the " +
  331. visitingTeam);
  332. score2 = keyboard.nextInt();
  333. keyboard.nextLine();
  334. // TASK #4
  335. // Execute an update to the Games table to
  336. // store the score for each team of that
  337. // game number
  338. if(score1 < score2)
  339. {
  340. // TASK #4
  341. // Retrieve the number from the appropriate column
  342. // (wins, losses, or ties) for the home team,
  343. // increment, and update that team's record.
  344. // Do the same for the visiting team
  345. }
  346. else if(score2 < score1)
  347. {
  348. // TASK #4
  349. // Retrieve the number from the appropriate column
  350. // (wins, losses, or ties) for the home team,
  351. // increment, and update that team's record.
  352. // Do the same for the visiting team
  353. }
  354. else
  355. {
  356. // TASK #4
  357. // Retrieve the number from the appropriate column
  358. // (wins, losses, or ties) for the home team,
  359. // increment, and update that team's record.
  360. // Do the same for the visiting team
  361. }
  362. }
  363. System.out.print("Do you want to enter another game: ");
  364. ans = keyboard.nextLine().charAt(0);
  365. } while(ans == 'Y'|| ans == 'y');
  366. }
  367. catch(Exception ex)
  368. {
  369. System.out.println("ERROR: " + ex.getMessage());
  370. }
  371. }
  372. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement