Advertisement
Guest User

Untitled

a guest
Mar 20th, 2017
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 14.47 KB | None | 0 0
  1.  
  2.  
  3. import java.sql.*;
  4. import java.util.Scanner;
  5. import java.util.logging.Level;
  6. import java.util.logging.Logger;
  7.  
  8. /**
  9.  *
  10.  * @author Mimi Opkins with some tweaking from Dave Brown
  11.  */
  12. public class JDBC_Project {
  13.     //  Database credentials
  14.     static String USER;
  15.     static String PASS;
  16.     static String DBNAME;
  17.     //This is the specification for the printout that I'm doing:
  18.     //each % denotes the start of a new field.
  19.     //The - denotes left justification.
  20.     //The number indicates how wide to make the field.
  21.     //The "s" denotes that it's a string.  All of our output in this test are
  22.     //strings, but that won't always be the case.
  23.     static final String displayFormat="%-5s%-15s%-15s%-15s\n";
  24. // JDBC driver name and database URL
  25.     static final String JDBC_DRIVER = "org.apache.derby.jdbc.ClientDriver";
  26.     static String DB_URL = "jdbc:derby://localhost:1527/";
  27. //            + "testdb;user=";
  28. /**
  29.  * Takes the input string and outputs "N/A" if the string is empty or null.
  30.  * @param input The string to be mapped.
  31.  * @return  Either the input string or "N/A" as appropriate.
  32.  */
  33.     public static String dispNull (String input) {
  34.         //because of short circuiting, if it's null, it never checks the length.
  35.         if (input == null || input.length() == 0)
  36.             return "N/A";
  37.         else
  38.             return input;
  39.     }
  40.    
  41.     public static int menu(Scanner in){
  42.         int x = 0;
  43.         do{
  44.             System.out.println("What do you want to do?");
  45.             System.out.println("1. List all writing groups");
  46.             System.out.println("2. List all data for a specific groups");
  47.             System.out.println("3. List all publishers");
  48.             System.out.println("4. List all data for a specific publisher");
  49.             System.out.println("5. List all book titles");
  50.             System.out.println("6. List all data for a specific book");
  51.             System.out.println("7. Insert a new book");
  52.             System.out.println("8. Insert new publisher");
  53.             System.out.println("9. Quit");
  54.            
  55.             x = in.nextInt();
  56.             in.nextLine();
  57.         } while(x < 1 || x > 9);
  58.         return x;
  59.     }
  60.    
  61.     public static void writingGroupRS(PreparedStatement g_name, String input){
  62.         ResultSet rs = null;
  63.         try {
  64.             g_name.setString(1, input);
  65.             g_name.execute();
  66.             rs = g_name.getResultSet();
  67.             while (rs.next()) {
  68.                 //Retrieve by column name
  69.                 String group_name = rs.getString("GROUP_NAME");
  70.                 String head_writer = rs.getString("HEAD_WRITER");
  71.                 String year_formed = rs.getString("YEAR_FORMED");
  72.                 String subject = rs.getString("SUBJECT");
  73.  
  74.                 //Display values
  75.                 System.out.println("Group Name: " + dispNull(group_name));
  76.                 System.out.println("Head Writer: " + dispNull(head_writer));
  77.                 System.out.println("Year Formed: " + dispNull(year_formed));
  78.                 System.out.println("Subject: " + dispNull(subject));
  79.             }
  80.         } catch (SQLException ex) {
  81.             ex.printStackTrace();
  82.         }
  83.     }
  84.     public static void publisherRS(PreparedStatement p_name, String input){
  85.         ResultSet rs = null;
  86.         try{
  87.             p_name.setString(1, input);
  88.             p_name.execute();
  89.             rs = p_name.getResultSet();
  90.             while (rs.next()) {
  91.                 //Retrieve by column name
  92.                 String pub_name = rs.getString("PUBLISHER_NAME");
  93.                 String pub_add = rs.getString("PUBlISHER_ADDRESS");
  94.                 String pub_phone = rs.getString("PUBLISHER_PHONE");
  95.                 String pub_email = rs.getString("PUBLISHER_EMAIL");
  96.  
  97.                 //Display values
  98.                 System.out.println("Publisher Name: " + dispNull(pub_name));
  99.                 System.out.println("Publisher Address: " + dispNull(pub_add));
  100.                 System.out.println("Publisher Phone: " + dispNull(pub_phone));
  101.                 System.out.println("Publisher Email: " + dispNull(pub_email));
  102.             }
  103.         } catch (SQLException ex) {
  104.             ex.printStackTrace();
  105.         }
  106.     }
  107.    
  108.     public static void bookRS(PreparedStatement b_name, String input, Connection conn){
  109.         ResultSet rs = null;
  110.         try{
  111.             b_name.setString(1, input);
  112.             b_name.execute();
  113.             rs = b_name.getResultSet();
  114.             while (rs.next()) {
  115.                 //Retrieve by column name
  116.                 String group_name = rs.getString("GROUP_NAME");
  117.                 String book_title = rs.getString("BOOK_TITLE");
  118.                 String pub_name = rs.getString("PUBLISHER_NAME");
  119.                 String numOfPages = rs.getString("NUMOFPAGES");
  120.  
  121.                 //Display values
  122.                 System.out.println("Group Name: " + dispNull(group_name));
  123.                 System.out.println();
  124.                 writingGroupRS(conn.prepareStatement("SELECT * FROM WRITINGGROUPS WHERE GROUP_NAME = ?"), group_name);
  125.                 System.out.println();
  126.                 System.out.println("Book Title: " + dispNull(book_title));
  127.                 System.out.println("Publisher Name: " + dispNull(pub_name));
  128.                 System.out.println();
  129.                 publisherRS(conn.prepareStatement("SELECT * FROM PUBLISHERS WHERE PUBLISHER_NAME = ?"), pub_name);
  130.                 System.out.println();
  131.                 System.out.println("Number of Pages: " + dispNull(numOfPages));
  132.             }
  133.         } catch (SQLException ex) {
  134.             ex.printStackTrace();
  135.         }
  136.     }
  137.    
  138.     public static void listAllBooks(Statement stmt){
  139.         String sql = "SELECT * FROM BOOKS";
  140.         try{
  141.             ResultSet rs = stmt.executeQuery(sql);
  142.             //STEP 5: Extract data from result set
  143.             System.out.println("Book Titles:");
  144.             while (rs.next()) {
  145.                 //Retrieve by column name
  146.                 String group_name = rs.getString("BOOK_TITLE");
  147.                 //Display values
  148.                 System.out.println(dispNull(group_name));
  149.         }
  150.         } catch (SQLException e){
  151.             e.printStackTrace();
  152.         }
  153.     }
  154.    
  155.     public static void listAllPubs(Statement stmt){
  156.         String sql = "SELECT * FROM PUBLISHERS";
  157.         try{
  158.             ResultSet rs = stmt.executeQuery(sql);
  159.             //STEP 5: Extract data from result set
  160.             System.out.println("Publisher Name:");
  161.             while (rs.next()) {
  162.                 //Retrieve by column name
  163.                 String group_name = rs.getString("PUBLISHER_NAME");
  164.                 //Display values
  165.                 System.out.println(dispNull(group_name));
  166.             }
  167.         } catch(SQLException e){
  168.             e.printStackTrace();
  169.         }
  170.     }
  171.    
  172.     public static void listAllGroups(Statement stmt){
  173.         String sql = "SELECT * FROM WRITINGGROUPS";
  174.         try{
  175.             ResultSet rs = stmt.executeQuery(sql);
  176.             //STEP 5: Extract data from result set
  177.             System.out.println("Group Name:");
  178.             while (rs.next()) {
  179.                 //Retrieve by column name
  180.                 String group_name = rs.getString("GROUP_NAME");
  181.                 //Display values
  182.                 System.out.println(dispNull(group_name));
  183.             }
  184.         } catch(SQLException e){
  185.             e.printStackTrace();
  186.         }
  187.     }
  188.    
  189.     public static String insertNewPublisher(Scanner in, Connection conn){
  190.         String pName, pAdd, pPhone, pEmail;
  191.         String sql = "INSERT INTO PUBLISHERS VALUES(?, ?, ?, ?)";
  192.                  
  193.         System.out.print("Enter publisher name: ");
  194.         pName = in.nextLine();
  195.         System.out.print("Enter publisher address: ");
  196.         pAdd = in.nextLine();
  197.         System.out.print("Enter publisher phone: ");
  198.         pPhone = in.nextLine();
  199.         System.out.print("Enter publisher email: ");
  200.         pEmail = in.nextLine();
  201.         try{
  202.             PreparedStatement b_name = conn.prepareStatement(sql);
  203.             b_name.setString(1, pName);
  204.             b_name.setString(2, pAdd);
  205.             b_name.setString(3, pPhone);
  206.             b_name.setString(4, pEmail);
  207.         }catch (SQLException e){
  208.             e.printStackTrace();
  209.         }
  210.         return pName;
  211.     }
  212.    
  213.     public static void main(String[] args) {
  214.         //Prompt the user for the database name, and the credentials.
  215.         //If your database has no credentials, you can update this code to
  216.         //remove that from the connection string.
  217.         Scanner in = new Scanner(System.in);
  218.         System.out.print("Name of the database (not the user account): ");
  219.         DBNAME = in.nextLine();
  220.         System.out.print("Database user name: ");
  221.         USER = in.nextLine();
  222.         System.out.print("Database password: ");
  223.         PASS = in.nextLine();
  224.         //Constructing the database URL connection string
  225.         DB_URL = DB_URL + DBNAME + ";user="+ USER + ";password=" + PASS;
  226.         Connection conn = null; //initialize the connection
  227.         Statement stmt = null;  //initialize the statement that we're using
  228.         ResultSet rs = null;  //Initialize the result set
  229.         try {
  230.             //STEP 2: Register JDBC driver
  231.             Class.forName("org.apache.derby.jdbc.ClientDriver");
  232.  
  233.             //STEP 3: Open a connection
  234.             System.out.println("Connecting to database...");
  235.             conn = DriverManager.getConnection(DB_URL);
  236.             System.out.println("Connected!");
  237.            
  238.             //Ask user what to do with database
  239.             int choice = 0;
  240.             while(choice != 9){
  241.                 choice = menu(in);
  242.  
  243.                 //STEP 4: Execute a query
  244.                 stmt = conn.createStatement();
  245.                 String sql = "";
  246.  
  247.  
  248.                 if(choice == 1){
  249.                     listAllGroups(stmt);
  250.                 }
  251.                 else if(choice == 2){
  252.                     PreparedStatement g_name = null;
  253.                     sql = "SELECT * FROM WRITINGGROUPS WHERE GROUP_NAME = ?";
  254.                     g_name = conn.prepareStatement(sql);
  255.                     System.out.print("Enter the group name: ");
  256.                     String input = in.nextLine();
  257.                     writingGroupRS(g_name, input);
  258.                 }
  259.                 else if(choice == 3){
  260.                     listAllPubs(stmt);
  261.                 }
  262.                 else if(choice == 4){
  263.                     PreparedStatement p_name = null;
  264.                     sql = "SELECT * FROM PUBLISHERS WHERE PUBLISHER_NAME = ?";
  265.                     p_name = conn.prepareStatement(sql);
  266.                     System.out.print("Enter the publisher's name: ");
  267.                     String input = in.nextLine();
  268.                     publisherRS(p_name, input);
  269.                 }
  270.                 else if(choice == 5){
  271.                     listAllBooks(stmt);
  272.                 }
  273.                 else if(choice == 6){
  274.                     PreparedStatement b_name = null;
  275.                     sql = "SELECT * FROM BOOKS WHERE BOOK_TITLE = ?";
  276.                     b_name = conn.prepareStatement(sql);
  277.                     System.out.print("Enter the book's title: ");
  278.                     String input = in.nextLine();
  279.                     bookRS(b_name, input, conn);
  280.                 }
  281.                 else if(choice == 7){
  282.                     PreparedStatement bookSQL = null;
  283.                     String pubName = "" , group = "";
  284.                    
  285.                     listAllPubs(stmt);
  286.                     while(true){
  287.                         System.out.print("Enter publisher name: ");
  288.                         pubName = in.nextLine();
  289.                         bookSQL = conn.prepareStatement("SELECT PUBLISHER_NAME FROM PUBLISHERS WHERE PUBLISHER_NAME = ?");
  290.                         bookSQL.setString(1, pubName);
  291.                         rs = bookSQL.executeQuery();
  292.                         if(rs.next())
  293.                             break;
  294.                         System.out.println("Publisher does not exist! Try Again");
  295.                     }
  296.                    
  297.                     listAllGroups(stmt);
  298.                     while(true){
  299.                         System.out.print("Enter book group's name: ");
  300.                         group = in.nextLine();
  301.                         bookSQL = conn.prepareStatement("SELECT GROUP_NAME FROM WRITINGGROUPS WHERE GROUP_NAME = ?");
  302.                         bookSQL.setString(1, group);
  303.                         rs = bookSQL.executeQuery();
  304.                         if(rs.next())
  305.                             break;
  306.                         System.out.println("Group does not exist! Try Again");
  307.                     }
  308.                
  309.                     System.out.print("Enter the book's title: ");
  310.                     String title = in.nextLine();
  311.                     System.out.print("Enter the year published: ");
  312.                     String year = in.nextLine();
  313.                     System.out.print("Enter the number of pages: ");
  314.                     String pages = in.nextLine();
  315.                    
  316.                    
  317.                     sql = "INSERT INTO BOOKS VALUES(?,?,?,?,?)";
  318.                     bookSQL = conn.prepareStatement(sql);
  319.                     bookSQL.setString(1, group);
  320.                     bookSQL.setString(2, title);
  321.                     bookSQL.setString(3, pubName);
  322.                     bookSQL.setString(4, year);
  323.                     bookSQL.setString(5, pages);
  324.                     bookSQL.execute();
  325.                     //rs = book.getResultSet();
  326.                 }
  327.                
  328.             }
  329.             //STEP 6: Clean-up environment
  330.             rs.close();
  331.             stmt.close();
  332.             conn.close();
  333.         } catch (SQLException se) {
  334.             //Handle errors for JDBC
  335.             se.printStackTrace();
  336.         } catch (Exception e) {
  337.             //Handle errors for Class.forName
  338.             e.printStackTrace();
  339.         } finally {
  340.             //finally block used to close resources
  341.             try {
  342.                 if (stmt != null) {
  343.                     stmt.close();
  344.                 }
  345.             } catch (SQLException se2) {
  346.             }// nothing we can do
  347.             try {
  348.                 if (conn != null) {
  349.                     conn.close();
  350.                 }
  351.             } catch (SQLException se) {
  352.                 se.printStackTrace();
  353.             }//end finally try
  354.         }//end try
  355.         System.out.println("Goodbye!");
  356.     }//end main
  357. }//end FirstExample}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement