Advertisement
Guest User

DB lab4 java handler

a guest
Jun 16th, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 5.73 KB | None | 0 0
  1. package de.haw.ie4lab4;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DatabaseMetaData;
  5. import java.sql.DriverManager;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import java.sql.SQLException;
  9.  
  10. public class DbHandler {
  11.   /**
  12.    * Database connection
  13.    */
  14.   private Connection conn;
  15.  
  16.   /**
  17.    * The current SQL statement
  18.    */
  19.   private String sql;
  20.  
  21.   /**
  22.    * Getter for the current SQL statement
  23.    *
  24.    * @return the SQL statement
  25.    */
  26.   public String getSql() {
  27.     return sql;
  28.   }
  29.  
  30.   /**
  31.    * Connect to the database.
  32.    *
  33.    * @param driverName
  34.    *          - name of JDBC driver class
  35.    * @param url
  36.    *          - JDBC URL
  37.    * @param user
  38.    *          - DB user name
  39.    * @param password
  40.    *          - DB password
  41.    * @throws SQLException
  42.    */
  43.  
  44.   public void connectDB(String driverName, String url, String user, String password) throws SQLException {
  45.     System.out.println("Trying to connect to " + url);
  46.  
  47.     // TODO: connect to the DB! -> done
  48.     conn = DriverManager.getConnection(url, user, password);
  49.  
  50.     // TODO: disable autoCommit! -> done
  51.     conn.setAutoCommit(false);
  52.     //
  53.     // Print success message and some meta data:
  54.     //
  55.     DatabaseMetaData metaData = conn.getMetaData();
  56.     System.out.println("Connected to DB " + metaData.getURL() + " as user " + metaData.getUserName());
  57.     System.out.println(metaData.getDatabaseProductName() + " " + metaData.getDatabaseMajorVersion() + "."
  58.         + metaData.getDatabaseMinorVersion());
  59.   }
  60.  
  61.   /**
  62.    * Close the connection
  63.  * @throws SQLException
  64.    */
  65.   public void close() throws SQLException {
  66.     /*
  67.      * TODO: rollback the transaction (in real life, you'd want to commit -> but
  68.      * then you cannot call insertNewCustomer() twice.)  -> done
  69.      */
  70.       conn.rollback();
  71.     // TODO: close the connection (if it has been initialized) -> done
  72.       if (conn != null) {
  73.           conn.close();
  74.       }
  75.   }
  76.  
  77.   /**
  78.    * Print the list of order numbers for the given customer
  79.    *
  80.    * @param customer
  81.    *          - Name of customer
  82.    * @throws SQLException
  83.    */
  84.   public void printOrderNumbers(String customer) throws SQLException {
  85.     System.out.println(customer + "'s orders:");
  86.  
  87.     // TODO: SQL see assignment 10b-10
  88.     sql = "SELECT orders.o_nr FROM orders" +
  89.             "JOIN customer ON orders.c_id = customer.c_id"+
  90.             " WHERE customer.name = ?";
  91.     PreparedStatement statement = conn.prepareStatement(sql);
  92.     statement.setString(1, customer);
  93.    
  94.     // cursor
  95.     ResultSet cursor = statement.executeQuery();
  96.     while (cursor.next()) {
  97.         cursor.getString(cursor.getString("o_nr"));
  98.     }
  99.   }
  100.  
  101.   /**
  102.    * Print an invoice for the given order. The invoice shall contain every
  103.    * single order item and the total price.
  104.    *
  105.    * @param orderNumber
  106.    *          - value for o_nr
  107.    * @throws SQLException
  108.    */
  109.   public void printInvoiceForOrder(int orderNumber) throws SQLException {
  110.     System.out.println("Invoice for order number " + orderNumber);
  111.  
  112.     // Optional: You could print customer information here!
  113.  
  114.     /*
  115.      * TODO: For every order item, print the article name, the article's price
  116.      * per unit, the quantity, and the price of the order item. SQL see
  117.      * assignment 10b-14
  118.      */
  119.     sql = "SELECT article.name, article.price, order_item.quantity, article.price * order_item.quantity AS Total FROM order_item"+
  120.             "JOIN orders ON order_item.o_nr = orders.o_nr"+
  121.             "JOIN article ON order_item.a_nr = article.a_nr"+
  122.             "WHERE order_item.o_nr = ?";
  123.     PreparedStatement statement = conn.prepareStatement(sql);
  124.     statement.setString(1, ""+orderNumber);
  125.    
  126.     ResultSet cursor = statement.executeQuery();
  127.     System.out.println("article     price     quantity     Total");
  128.     // this saves the total price of the order
  129.     double totalPrice = 0;
  130.     while (cursor.next()) {
  131.         System.out.println(cursor.getString("name")+"|"+
  132.                 cursor.getString("price")+"|"+
  133.                 cursor.getString("quantity")+"|"+
  134.                 cursor.getString("Total"));
  135.        
  136.         totalPrice += Double.parseDouble(cursor.getString("Total"));
  137.     }
  138.  
  139.     System.out.println("-----------------------");
  140.  
  141.     /*
  142.      * TODO: Print the total price of the order. You can calculate the sum via
  143.      * SQL (see assignment 10b-15), or in Java.
  144.      */
  145.     sql = "";
  146.     System.out.println("Total price: " + totalPrice);
  147.  
  148.   }
  149.  
  150.   /**
  151.    * Insert a new customer
  152.    *
  153.    * @param id
  154.    *          - customer ID
  155.    * @param name
  156.    *          - customer name
  157.    * @throws SQLException
  158.    */
  159.   public void insertNewCustomer(int id, String name) throws SQLException {
  160.     System.out.println("Trying to insert new customer. id=" + id + ", name=" + name);
  161.  
  162.     // TODO: insert a new customer with the given values
  163.     sql = "INSERT INTO customer (c_id, name) VALUES (?,?)";
  164.     PreparedStatement statement = conn.prepareStatement(sql);
  165.     statement.setInt(1, id);
  166.     statement.setString(2, name);
  167.    
  168.     statement.execute();
  169.    
  170.   }
  171.  
  172.   /**
  173.    * Change the article's price
  174.    *
  175.    * @param articleName
  176.    *          - identifies the article
  177.    * @param price
  178.    *          - the new price
  179.    * @throws SQLException
  180.    */
  181.   public void changeArticlePrice(String articleName, double price) throws SQLException {
  182.     System.out.println("Trying to set the price of " + articleName + " to " + price);
  183.     sql = "UPDATE article SET price = ? WHERE name = ?";
  184.     PreparedStatement statement = conn.prepareStatement(sql);
  185.     statement.setDouble(1, price);  
  186.     statement.setString(2, articleName);
  187.    
  188.     statement.execute();
  189.     int n = 0;
  190.  
  191.     // TODO: change the article's price
  192.     sql = "";
  193.  
  194.     System.out.println("Number of rows affected: " + n);
  195.   }
  196. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement