Advertisement
Guest User

Untitled

a guest
Mar 21st, 2017
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 22.36 KB | None | 0 0
  1. import java.sql.*;
  2. import java.util.Scanner;
  3. import java.util.logging.Level;
  4. import java.util.logging.Logger;
  5.  
  6. /**
  7.  *
  8.  * @author Stefin Mathew and Jorge Martinez
  9.  */
  10. public class JDBC_Project {
  11.     //  Database credentials
  12.     static String USER;
  13.     static String PASS;
  14.     static String DBNAME;
  15.  
  16.     static String DB_URL = "jdbc:derby://localhost:1527/";
  17. //            + "testdb;user=";
  18. /**
  19.  * Takes the input string and outputs "N/A" if the string is empty or null.
  20.  * @param input The string to be mapped.
  21.  * @return  Either the input string or "N/A" as appropriate.
  22.  */
  23.     public static String dispNull (String input) {
  24.         //because of short circuiting, if it's null, it never checks the length.
  25.         if (input == null || input.length() == 0)
  26.             return "N/A";
  27.         else
  28.             return input;
  29.     }
  30.     /**
  31.      * Displays the menu for the user to choose which functions of the database to perform
  32.      * @param in    Scanner object to get input from user
  33.      * @return  The choice of user in integer format
  34.      */
  35.     public static int menu(Scanner in){
  36.         int x = 0;
  37.         do{
  38.             System.out.println("What do you want to do?");
  39.             System.out.println("1. List all writing groups");
  40.             System.out.println("2. List all data for a specific groups");
  41.             System.out.println("3. List all publishers");
  42.             System.out.println("4. List all data for a specific publisher");
  43.             System.out.println("5. List all book titles");
  44.             System.out.println("6. List all data for a specific book");
  45.             System.out.println("7. Insert a new book");
  46.             System.out.println("8. Insert new publisher");
  47.             System.out.println("9. Delete a book");
  48.             System.out.println("10. Quit");
  49.            
  50.             x = in.nextInt();
  51.             in.nextLine();
  52.         } while(x < 1 || x > 10);
  53.         return x;
  54.     }
  55.     /**
  56.      * Displays the details of the a particular writing group
  57.      * @param g_name    PreparedStatement object used to execute SQL statements.
  58.      * @param input The name of the writing group
  59.      */
  60.     public static void writingGroupRS(PreparedStatement g_name, String input){
  61.         ResultSet rs = null;
  62.         try {
  63.             g_name.setString(1, input);
  64.             g_name.execute();
  65.             rs = g_name.getResultSet();
  66.             while (rs.next()) {
  67.                 //Retrieve by column name
  68.                 String group_name = rs.getString("GROUP_NAME");
  69.                 String head_writer = rs.getString("HEAD_WRITER");
  70.                 String year_formed = rs.getString("YEAR_FORMED");
  71.                 String subject = rs.getString("SUBJECT");
  72.  
  73.                 //Display values
  74.                 System.out.println("Group Name: " + dispNull(group_name));
  75.                 System.out.println("Head Writer: " + dispNull(head_writer));
  76.                 System.out.println("Year Formed: " + dispNull(year_formed));
  77.                 System.out.println("Subject: " + dispNull(subject));
  78.             }
  79.         } catch (SQLException ex) {
  80.             ex.printStackTrace();
  81.         }
  82.     }
  83.     /**
  84.      * Displays the details of the a particular publisher
  85.      * @param p_name    PreparedStatement object used to execute SQL statements.
  86.      * @param input The name of the publisher
  87.      */
  88.     public static void publisherRS(PreparedStatement p_name, String input){
  89.         ResultSet rs = null;
  90.         try{
  91.             p_name.setString(1, input);
  92.             p_name.execute();
  93.             rs = p_name.getResultSet();
  94.             while (rs.next()) {
  95.                 //Retrieve by column name
  96.                 String pub_name = rs.getString("PUBLISHER_NAME");
  97.                 String pub_add = rs.getString("PUBlISHER_ADDRESS");
  98.                 String pub_phone = rs.getString("PUBLISHER_PHONE");
  99.                 String pub_email = rs.getString("PUBLISHER_EMAIL");
  100.  
  101.                 //Display values
  102.                 System.out.println("Publisher Name: " + dispNull(pub_name));
  103.                 System.out.println("Publisher Address: " + dispNull(pub_add));
  104.                 System.out.println("Publisher Phone: " + dispNull(pub_phone));
  105.                 System.out.println("Publisher Email: " + dispNull(pub_email));
  106.             }
  107.         } catch (SQLException ex) {
  108.             ex.printStackTrace();
  109.         }
  110.     }
  111.     /**
  112.      * Displays the details of the a particular book
  113.      * @param b_name    PreparedStatement object used to execute SQL statements.
  114.      * @param input The name of the book
  115.      * @param conn Connection object used to execute SQL statements that involve the database connection
  116.      */
  117.     public static void bookRS(PreparedStatement b_name, String input, Connection conn){
  118.         ResultSet rs = null;
  119.         try{
  120.             b_name.setString(1, input);
  121.             b_name.execute();
  122.             rs = b_name.getResultSet();
  123.             while (rs.next()) {
  124.                 //Retrieve by column name
  125.                 String group_name = rs.getString("GROUP_NAME");
  126.                 String book_title = rs.getString("BOOK_TITLE");
  127.                 String pub_name = rs.getString("PUBLISHER_NAME");
  128.                 String year_pub = rs.getString("YEAR_PUBLISHED");
  129.                 String numOfPages = rs.getString("NUMOFPAGES");
  130.  
  131.                 //Display values
  132.                 //System.out.println("Group Name: " + dispNull(group_name));
  133.                 System.out.println("Book Title: " + dispNull(book_title));
  134.                 System.out.println();
  135.                 writingGroupRS(conn.prepareStatement("SELECT * FROM WRITINGGROUPS WHERE GROUP_NAME = ?"), group_name);
  136.                 System.out.println();
  137.                 publisherRS(conn.prepareStatement("SELECT * FROM PUBLISHERS WHERE PUBLISHER_NAME = ?"), pub_name);
  138.                 System.out.println();
  139.                 System.out.println("Year Published: " + dispNull(year_pub));
  140.                 System.out.println();
  141.                 System.out.println("Number of Pages: " + dispNull(numOfPages));
  142.             }
  143.         } catch (SQLException ex) {
  144.             ex.printStackTrace();
  145.         }
  146.     }
  147.     /**
  148.      * Displays all the books in the database
  149.      * @param stmt Statement object used to create a ResultSet
  150.      */
  151.     public static void listAllBooks(Statement stmt){
  152.         String sql = "SELECT * FROM BOOKS";
  153.         try{
  154.             ResultSet rs = stmt.executeQuery(sql);
  155.             //STEP 5: Extract data from result set
  156.             System.out.println("Book Titles:");
  157.             while (rs.next()) {
  158.                 //Retrieve by column name
  159.                 String group_name = rs.getString("BOOK_TITLE");
  160.                 //Display values
  161.                 System.out.println(dispNull(group_name));
  162.         }
  163.         } catch (SQLException e){
  164.             e.printStackTrace();
  165.         }
  166.     }
  167.     /**
  168.      * Displays all the publishers in the database
  169.      * @param stmt Statement object used to create a ResultSet
  170.      */
  171.     public static void listAllPubs(Statement stmt){
  172.         String sql = "SELECT * FROM PUBLISHERS";
  173.         try{
  174.             ResultSet rs = stmt.executeQuery(sql);
  175.             //STEP 5: Extract data from result set
  176.             System.out.println("Publisher Name:");
  177.             while (rs.next()) {
  178.                 //Retrieve by column name
  179.                 String group_name = rs.getString("PUBLISHER_NAME");
  180.                 //Display values
  181.                 System.out.println(dispNull(group_name));
  182.             }
  183.         } catch(SQLException e){
  184.             e.printStackTrace();
  185.         }
  186.     }
  187.     /**
  188.      * Displays all the writing groups in the database
  189.      * @param stmt Statement object used to create a ResultSet
  190.      */
  191.     public static void listAllGroups(Statement stmt){
  192.         String sql = "SELECT * FROM WRITINGGROUPS";
  193.         try{
  194.             ResultSet rs = stmt.executeQuery(sql);
  195.             //STEP 5: Extract data from result set
  196.             System.out.println("Group Name:");
  197.             while (rs.next()) {
  198.                 //Retrieve by column name
  199.                 String group_name = rs.getString("GROUP_NAME");
  200.                 //Display values
  201.                 System.out.println(dispNull(group_name));
  202.             }
  203.         } catch(SQLException e){
  204.             e.printStackTrace();
  205.         }
  206.     }
  207.    
  208.     public static String insertNewPublisher(Scanner in, Connection conn){
  209.         String pName, pAdd, pPhone, pEmail;
  210.         String sql = "INSERT INTO PUBLISHERS VALUES(?, ?, ?, ?)";
  211.                  
  212.         System.out.print("Enter publisher name: ");
  213.         pName = in.nextLine();
  214.         System.out.print("Enter publisher address: ");
  215.         pAdd = in.nextLine();
  216.         System.out.print("Enter publisher phone: ");
  217.         pPhone = in.nextLine();
  218.         System.out.print("Enter publisher email: ");
  219.         pEmail = in.nextLine();
  220.         try{
  221.             PreparedStatement b_name = conn.prepareStatement(sql);
  222.             b_name.setString(1, pName);
  223.             b_name.setString(2, pAdd);
  224.             b_name.setString(3, pPhone);
  225.             b_name.setString(4, pEmail);
  226.         }catch (SQLException e){
  227.             e.printStackTrace();
  228.         }
  229.         return pName;
  230.     }
  231.    
  232.     public static void main(String[] args) {
  233.         //Prompt the user for the database name, and the credentials.
  234.         //If your database has no credentials, you can update this code to
  235.         //remove that from the connection string.
  236.         Scanner in = new Scanner(System.in);
  237.         System.out.print("Name of the database (not the user account): ");
  238.         DBNAME = in.nextLine();
  239.         System.out.print("Database user name: ");
  240.         USER = in.nextLine();
  241.         System.out.print("Database password: ");
  242.         PASS = in.nextLine();
  243.         //Constructing the database URL connection string
  244.         DB_URL = DB_URL + DBNAME + ";user="+ USER + ";password=" + PASS;
  245.         Connection conn = null; //initialize the connection
  246.         Statement stmt = null;  //initialize the statement that we're using
  247.         ResultSet rs = null;  //Initialize the result set
  248.         try {
  249.             //STEP 2: Register JDBC driver
  250.             Class.forName("org.apache.derby.jdbc.ClientDriver");
  251.  
  252.             //STEP 3: Open a connection
  253.             System.out.println("Connecting to database...");
  254.             conn = DriverManager.getConnection(DB_URL);
  255.             System.out.println("Connected!");
  256.            
  257.             //Ask user what to do with database
  258.             int choice = 0;
  259.             while(choice != 10){
  260.                 choice = menu(in);
  261.  
  262.                 //STEP 4: Execute a query
  263.                 stmt = conn.createStatement();
  264.                 String sql = "";
  265.  
  266.  
  267.                 if(choice == 1){
  268.                     listAllGroups(stmt);
  269.                 }
  270.                 else if(choice == 2){
  271.                     PreparedStatement g_name = null;
  272.                     String group = "";
  273.                     listAllGroups(stmt);
  274.                     while(true){
  275.                         System.out.print("Enter book group's name: ");
  276.                         group = in.nextLine();
  277.                         g_name = conn.prepareStatement("SELECT * FROM WRITINGGROUPS WHERE GROUP_NAME = ?");
  278.                         g_name.setString(1, group);
  279.                         rs = g_name.executeQuery();
  280.                         if(rs.next())
  281.                             break;
  282.                         System.out.println("Group does not exist! Try Again");
  283.                     }
  284.                    
  285.                     writingGroupRS(g_name, group);
  286.                 }
  287.                 else if(choice == 3){
  288.                     listAllPubs(stmt);
  289.                 }
  290.                 else if(choice == 4){
  291.                     PreparedStatement p_name = null;
  292.                     String pubName = "";
  293.                     listAllPubs(stmt);
  294.                     while(true){
  295.                         System.out.print("Enter publisher name: ");
  296.                         pubName = in.nextLine();
  297.                         p_name = conn.prepareStatement("SELECT * FROM PUBLISHERS WHERE PUBLISHER_NAME = ?");
  298.                         p_name.setString(1, pubName);
  299.                         rs = p_name.executeQuery();
  300.                         if(rs.next())
  301.                             break;
  302.                         System.out.println("Publisher does not exist! Try Again");
  303.                     }
  304.                     publisherRS(p_name, pubName);
  305.                 }
  306.                 else if(choice == 5){
  307.                     listAllBooks(stmt);
  308.                 }
  309.                 else if(choice == 6){
  310.                     PreparedStatement b_name = null;
  311.                     String bookTitle = "";
  312.                     while(true){
  313.                         System.out.print("Enter book title: ");
  314.                         bookTitle = in.nextLine();
  315.                         b_name = conn.prepareStatement("SELECT * FROM BOOKS WHERE BOOK_TITLE = ?");
  316.                         b_name.setString(1, bookTitle);
  317.                         rs = b_name.executeQuery();
  318.                         if(rs.next())
  319.                             break;
  320.                         System.out.println("Book does not exist! Try Again");
  321.                     }
  322.                    
  323.                     bookRS(b_name, bookTitle, conn);
  324.                 }
  325.                 else if(choice == 7){
  326.                     PreparedStatement bookSQL = null;
  327.                     String pubName = "" , group = "";
  328.                    
  329.                     listAllPubs(stmt);
  330.                     while(true){
  331.                         System.out.print("Enter publisher name: ");
  332.                         pubName = in.nextLine();
  333.                         bookSQL = conn.prepareStatement("SELECT PUBLISHER_NAME FROM PUBLISHERS WHERE PUBLISHER_NAME = ?");
  334.                         bookSQL.setString(1, pubName);
  335.                         rs = bookSQL.executeQuery();
  336.                         if(rs.next())
  337.                             break;
  338.                         System.out.println("Publisher does not exist! Try Again");
  339.                     }
  340.                    
  341.                     listAllGroups(stmt);
  342.                     while(true){
  343.                         System.out.print("Enter book group's name: ");
  344.                         group = in.nextLine();
  345.                         bookSQL = conn.prepareStatement("SELECT GROUP_NAME FROM WRITINGGROUPS WHERE GROUP_NAME = ?");
  346.                         bookSQL.setString(1, group);
  347.                         rs = bookSQL.executeQuery();
  348.                         if(rs.next())
  349.                             break;
  350.                         System.out.println("Group does not exist! Try Again");
  351.                     }
  352.                
  353.                     System.out.print("Enter the book's title: ");
  354.                     String title = in.nextLine();
  355.                     System.out.print("Enter the year published: ");
  356.                     String year = in.nextLine();
  357.                     System.out.print("Enter the number of pages: ");
  358.                     String pages = in.nextLine();
  359.                    
  360.                    
  361.                     sql = "INSERT INTO BOOKS VALUES(?,?,?,?,?)";
  362.                     bookSQL = conn.prepareStatement(sql);
  363.                     bookSQL.setString(1, group);
  364.                     bookSQL.setString(2, title);
  365.                     bookSQL.setString(3, pubName);
  366.                     bookSQL.setString(4, year);
  367.                     bookSQL.setString(5, pages);
  368.                     bookSQL.execute();
  369.                     //rs = book.getResultSet();
  370.                 }
  371.                 else if(choice == 8){
  372.                     /*PreparedStatement object to be used*/
  373.                     PreparedStatement p_name = null;
  374.                     /*Get publisher user wishes to replace*/
  375.                     System.out.println("Which publisher is being bought off?");
  376.                     String oldPublisher = in.nextLine();
  377.                     /*Prepare to look for publisher*/
  378.                     rs = stmt.executeQuery("select * from PUBLISHERS");
  379.                     /*Will be true if publisher found in database*/
  380.                     boolean validPublisher = false;
  381.                     /*Check database for publisher to be removed*/
  382.                     while(rs.next()){
  383.                         if(rs.getString("PUBLISHER_NAME").equals(oldPublisher)){
  384.                             validPublisher = true;
  385.                         }
  386.                     }
  387.                     /*If publisher was not found, tell user and break*/
  388.                     if(validPublisher == false){
  389.                         System.out.println("That publisher is not in the data base....");
  390.                        
  391.                     }else{
  392.                         /*Get all information for new Publisher*/
  393.                         System.out.print("Enter publisher name: ");
  394.                         String pName = in.nextLine();
  395.                         System.out.print("Enter publisher address: ");
  396.                         String pAdd = in.nextLine();
  397.                         System.out.print("Enter publisher phone: ");
  398.                         String pPhone = in.nextLine();
  399.                         System.out.print("Enter publisher email: ");
  400.                         String email = in.nextLine();
  401.                         /*Create new publisher with attributes*/
  402.                         String sql2 = "insert into PUBLISHERS values(?,?,?,?)";
  403.                         p_name = conn.prepareStatement(sql2);
  404.                         p_name.setString(1, pName);
  405.                         p_name.setString(2, pAdd);
  406.                         p_name.setString(3, pPhone);
  407.                         p_name.setString(4, email);
  408.                         p_name.execute();
  409.                         /*Prepare to replace old publisher with new one*/
  410.                         rs = stmt.executeQuery("select * from BOOKS");
  411.                         while(rs.next()){
  412.                             if(rs.getString("PUBLISHER_NAME").equals(oldPublisher)){
  413.                                     /*Old publisher replaced*/
  414.                                     sql = "update BOOKS set PUBLISHER_NAME=? where PUBLISHER_NAME=?";
  415.                                     p_name = conn.prepareStatement(sql);
  416.                                     p_name.setString(1, pName);
  417.                                     p_name.setString(2,oldPublisher);
  418.                                     p_name.executeUpdate();
  419.                             }
  420.                         }
  421.                     }
  422.                     /*Delete old publisher*/
  423.                     PreparedStatement st = conn.prepareStatement("delete from PUBLISHERS where PUBLISHER_NAME= ?");
  424.                     st.setString(1, oldPublisher);
  425.                     st.executeUpdate();
  426.                     /*Debugging*/
  427.                     listAllPubs(stmt);
  428.                     listAllBooks(stmt);
  429.                 }
  430.                 else if(choice == 9){
  431.                     listAllBooks(stmt);
  432.                     PreparedStatement removeSQL = null;
  433.                     String removeBook = "";
  434.                     String pubName = "";
  435.                     while(true){
  436.                         System.out.print("Enter book title: ");
  437.                         removeBook = in.nextLine();
  438.                         removeSQL = conn.prepareStatement("SELECT COUNT(BOOK_TITLE) FROM BOOKS WHERE BOOK_TITLE = ?");
  439.                         removeSQL.setString(1, removeBook);
  440.                         rs = removeSQL.executeQuery();
  441.                         if(rs.next()){
  442.                             int duplicates = rs.getInt(1);
  443.                             if(duplicates == 1){
  444.                                 removeSQL = conn.prepareStatement("DELETE FROM BOOKS WHERE BOOK_TITLE = ?");
  445.                                 removeSQL.setString(1, removeBook);
  446.                                 removeSQL.execute();
  447.                                 System.out.println("Book Deleted!");
  448.                                 break;
  449.                             }
  450.                             else if(duplicates > 1){
  451.                                 listAllPubs(stmt);
  452.                                 System.out.print("Enter publisher name: ");
  453.                                 pubName = in.nextLine();
  454.                                 removeSQL = conn.prepareStatement("SELECT PUBLISHER_NAME FROM BOOKS WHERE PUBLISHER_NAME = ?");
  455.                                 removeSQL.setString(1, pubName);
  456.                                 rs = removeSQL.executeQuery();
  457.                                 if(rs.next()){
  458.                                     removeSQL = conn.prepareStatement("DELETE FROM BOOKS WHERE BOOK_TITLE = ? AND PUBLISHER_NAME = ?");
  459.                                     removeSQL.setString(1, removeBook);
  460.                                     removeSQL.setString(2, pubName);
  461.                                     removeSQL.execute();
  462.                                     System.out.println("Book Deleted!");
  463.                                     break;
  464.                                 }
  465.                                 System.out.println("Publisher does not exist! Try Again");
  466.                             }
  467.                         }
  468.                         System.out.println("Book does not exist! Try Again");
  469.                     }
  470.                     removeSQL = conn.prepareStatement("SELECT PUBLISHER_NAME FROM BOOKS WHERE BOOK_TITLE = ?");
  471.                     removeSQL.setString(1, removeBook);
  472.                     rs = removeSQL.executeQuery();
  473.                    
  474.                 }
  475.                
  476.             }
  477.             //STEP 6: Clean-up environment
  478.             rs.close();
  479.             stmt.close();
  480.             conn.close();
  481.         } catch (SQLException se) {
  482.             //Handle errors for JDBC
  483.             se.printStackTrace();
  484.         } catch (Exception e) {
  485.             //Handle errors for Class.forName
  486.             e.printStackTrace();
  487.         } finally {
  488.             //finally block used to close resources
  489.             try {
  490.                 if (stmt != null) {
  491.                     stmt.close();
  492.                 }
  493.             } catch (SQLException se2) {
  494.             }// nothing we can do
  495.             try {
  496.                 if (conn != null) {
  497.                     conn.close();
  498.                 }
  499.             } catch (SQLException se) {
  500.                 se.printStackTrace();
  501.             }//end finally try
  502.         }//end try
  503.         System.out.println("Goodbye!");
  504.     }
  505. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement