Guest User

Untitled

a guest
Oct 17th, 2017
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.51 KB | None | 0 0
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. import java.util.Scanner;
  7.  
  8.  
  9. public class SelectProductsByPrice {
  10. //DERBY SERVER CONNECTION STRING
  11. private static String dbURL = "jdbc:derby://localhost:1527/manfdb;create=false;";
  12. private static Connection conn = null;
  13. private static Statement stmt = null;
  14. //MAIN START
  15. public static void main(String[] args) throws SQLException {
  16. //SCRIPT START
  17. System.out.println("Give the price that you wish to get the number of PCs, Laptops, and Printers that are a higher price\nNote: it is case sensitive\n");
  18. //INPUT START
  19. System.out.println("Price: ");
  20. //GET INPUT
  21. Scanner sc = new Scanner(System.in);
  22. float price = Float.parseFloat(sc.nextLine());
  23. //BEGIN CONNECTION
  24. Connection conn = createConnection();
  25. //VARIABLES
  26. float numPcs = selectNumberOfProductsGreaterThanPrice("pc", price);
  27. float numLaptops = selectNumberOfProductsGreaterThanPrice("laptop", price);
  28. float numPrinters = selectNumberOfProductsGreaterThanPrice("printer", price);
  29.  
  30. System.out.println("\n\tNumber of PCs: " + numPcs + "\n");
  31. System.out.println("\tNumber of Laptops: " + numLaptops + "\n");
  32. System.out.println("\tNumber of Printers: " + numPrinters + "\n");
  33.  
  34. if(!conn.isClosed()) {
  35. System.out.println("\nClosing....");
  36. conn.close();
  37. }
  38. }
  39. //CREATE THE CONNECTION TO THE DERBY DATABASE
  40. private static Connection createConnection() {
  41. try {
  42. //GET DERBY DRIVER
  43. Class.forName("org.apache.derby.jdbc.ClientDriver").newInstance();
  44. //GET A CONNECTION
  45. conn = DriverManager.getConnection(dbURL);
  46. return conn;
  47. }
  48. catch (Exception except) {
  49. except.printStackTrace();
  50. }
  51. return null;
  52. }
  53. //GET COUNT OF PCS GREATER THAN PRICE
  54. private static float selectNumberOfProductsGreaterThanPrice(String tableName, float price) {
  55. try {
  56. //CREATE STATEMENT AND QUERY
  57. stmt = conn.createStatement();
  58. ResultSet results = stmt.executeQuery("select count(*) from " + tableName + " A where A.price > " + price);
  59. //PARSE RESULTS AND SAVE TO VECTOR
  60. while(results.next()) {
  61. return results.getFloat(1);
  62. }
  63. results.close();
  64. stmt.close();
  65. }
  66. catch (SQLException sqlExcept) {
  67. sqlExcept.printStackTrace();
  68. }
  69. return 1;
  70. }
  71. }
Add Comment
Please, Sign In to add comment