Advertisement
Guest User

Untitled

a guest
Dec 7th, 2016
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 9.38 KB | None | 0 0
  1. package info.goolap.beuth.jdbc.Storage.Person_DataAccessObject;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.Date;
  5. import java.sql.DriverManager;
  6. import java.sql.PreparedStatement;
  7. import java.sql.ResultSet;
  8. import java.sql.ResultSetMetaData;
  9. import java.sql.SQLException;
  10. import java.sql.Statement;
  11.  
  12. /**
  13.  * @author Alexander L�ser
  14.  * This class implements methods for RDBMS connectivity and methods for reading and writing from table person.
  15.  *
  16.  */
  17. public class Person_Storage {
  18.  
  19.    /* These variable values are used to setup the Connection object */
  20.    
  21.    private static final String DBNAME = "";
  22.    private static final String URL = "jdbc:oracle:thin:@dbl43.beuth-hochschule.de:1521:oracle";
  23.    private static final String USER = "";
  24.    private static final String PASSWORD = "";
  25.    private static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
  26.    private Connection con;
  27.    private PreparedStatement prepStatement_SELECT_PERSONS_WITH_YEAR;
  28.    private PreparedStatement prepStatement_INSERT_PERSON;
  29.    
  30.  
  31.    /*
  32.     This method is used to create a connection using
  33.    the values listed above. Notice the throws clause
  34.    in the method signature. This allows the calling method
  35.    to deal with the exception rather than catching it in
  36.    both places. The ClassNotFoundException must be caught
  37.    because the forName method requires it. */
  38.  
  39.    /**
  40.     * @param dbname
  41.     * @return
  42.     * @throws SQLException
  43.     *    
  44.     *  This method is used to create a connection using
  45.     *  the values listed above. Notice the throws clause
  46.     *  in the method signature. This allows the calling method
  47.     *  to deal with the exception rather than catching it in
  48.     *  both places. The ClassNotFoundException must be caught
  49.     *  because the forName method requires it.
  50.     */
  51.    private Connection connect(String dbname) throws SQLException {
  52.       Connection con = null;
  53.       try {
  54.          Class.forName(DRIVER);
  55.          con = DriverManager.getConnection(URL+dbname, USER, PASSWORD);
  56.       }
  57.       catch(ClassNotFoundException ex) {
  58.          System.exit(-1);
  59.       }
  60.       return con;
  61.    }
  62.  
  63.    /** This method prints out the records of table person. Note the try
  64.     *  and catch. Virtually all JDBC methods throw a
  65.     *  SQLException that must be tended to. The connection
  66.     *  object is used to create a statement object.
  67.     *  The executeQuery method is used to submit a
  68.     *  SELECT SQL query. The executeQuery method returns a ResultSet object.
  69.     */
  70.    public void printAllPersons() {
  71.       String query = Person_SQL_Statements.SELECT_STAR_FROM_PERSONS;
  72.       ResultSet rs = null;
  73.       try {
  74.          Statement s = con.createStatement();
  75.          long begin = System.currentTimeMillis();
  76.          rs = s.executeQuery(query);
  77.          long executiontime = System.currentTimeMillis()-begin;
  78.          this.printResultSet2Shell(rs,query,executiontime);
  79.          rs.close();
  80.          s.close();
  81.       }
  82.       catch(SQLException ex) {
  83.             // handle any errors
  84.             System.out.println("SQLException: " + ex.getMessage());
  85.             System.out.println("SQLState: " + ex.getSQLState());
  86.             System.out.println("VendorError: " + ex.getErrorCode());        
  87.             System.exit(-1);
  88.       }
  89.    }
  90.  
  91.    /**
  92.     * @param date
  93.     * This method reads records from the table person for a given date. It executes a prepared statement query.
  94.     */
  95.    public void getPerson_withYear(Date date) {
  96.        ResultSet rs = null;
  97.        try {
  98.            PreparedStatement pst = prepStatement_SELECT_PERSONS_WITH_YEAR;
  99.            pst.setDate(1, date);
  100.            long begin = System.currentTimeMillis();
  101.            rs = pst.executeQuery();
  102.            long executiontime = System.currentTimeMillis()-begin;
  103.            this.printResultSet2Shell(rs, rs.getStatement().toString(), executiontime);
  104.            rs.close();
  105.        }
  106.        catch(SQLException ex) {
  107.                 // handle any errors
  108.                 System.out.println("SQLException: " + ex.getMessage());
  109.                 System.out.println("SQLState: " + ex.getSQLState());
  110.                 System.out.println("VendorError: " + ex.getErrorCode());        
  111.                 System.exit(-1);
  112.        }
  113.     }  
  114.  
  115.    /** This method is used to open the DB and to print out
  116.    * the connection status.  
  117.  * @param prepStatement_INSERT_PERSON
  118.    */
  119.    public void openDB() throws SQLException {
  120.        con  = this.connect(DBNAME);
  121.        System.out.println("Connected to: " +
  122.                con.getMetaData().getDatabaseProductName() + " " +
  123.                con.getMetaData().getDatabaseProductVersion()
  124.         );
  125.        prepStatement_INSERT_PERSON = con.prepareStatement(Person_SQL_Statements.INSERT_PERSON);
  126.        prepStatement_SELECT_PERSONS_WITH_YEAR = con.prepareStatement(Person_SQL_Statements.SELECT_PERSONS_WITH_YEAR);
  127.     }
  128.  
  129.    /** This method opens a connection the DB and prints out
  130.     * the connection status.  
  131.     */
  132.    public void closeDB() throws SQLException {
  133.        prepStatement_INSERT_PERSON.close();
  134.        prepStatement_SELECT_PERSONS_WITH_YEAR.close();
  135.        con.close();
  136.        System.out.println("Connection is closed: "+ con.isClosed());
  137.    }
  138.  
  139.    
  140.    /**
  141.     * @param rs
  142.     * @param query
  143.     * @param executiontime
  144.     * @throws SQLException
  145.     *
  146.     * This method navigates through the records
  147.     * in the ResultSet object (the next method for
  148.     * example moves the cursor to the next row; it
  149.     * returns false when it runs out of rows) as well
  150.     * as methods to access fields in those rows.
  151.     * Notice that the person_id  fields is of  the  data
  152.     * type 'long', fields name and location are strings
  153.     * and field born_date is a date. The ResultSet
  154.     * object provides methods to deal with most common data
  155.     * types. Please  review how other java data types align
  156.     * with database data types. The report is
  157.     * formatted using the format method introduced in Java 5.  
  158.     * */
  159.    private void printResultSet2Shell(ResultSet rs, String query, long executiontime) throws SQLException
  160.    {
  161.        System.out.println("===============================================================");
  162.        System.out.println(query);
  163.        System.out.println("Execution Time: " + executiontime +"ms");
  164.        System.out.println("===============================================================");
  165.        System.out.format("%-20s %-15s %-15s %10s%n",
  166.            "PERSON_ID", "FIRST_NANE", "LAST_NAME", "BORN_DATE");
  167.        System.out.format("%-20s %-15s %-15s %10s%n",
  168.            "-------------------", "---------------",
  169.             "------------", "----------");
  170.  
  171.        while(rs.next()) {
  172.            long person_id = rs.getLong(Person_SQL_Statements.COL_person_id);
  173.            String first_name = rs.getString(Person_SQL_Statements.COL_first_name);
  174.            String last_name = rs.getString(Person_SQL_Statements.COL_last_name);
  175.            Date born_date = rs.getDate(Person_SQL_Statements.COL_born_date);
  176.            System.out.format("%-20d %-15s %-15s %10s %n",
  177.                    person_id, first_name, last_name, born_date);
  178.        }
  179.        System.out.println("================================================================");
  180.    }
  181.  
  182.     /**
  183.      *
  184.      * @param person_id
  185.      * @param first_name
  186.      * @param last_name
  187.      * @param born_date
  188.      * This method demonstrates an insert record operation. The method implements this functionality with
  189.      * a  prepared statement and an executeUpdate. Eventually, we can extend the method for update
  190.      * and delete operations as well.
  191.      */
  192.    public void insertPerson(long person_id, String first_name, String last_name, Date born_date)
  193.    {
  194.        try {
  195.            PreparedStatement pstmt = prepStatement_INSERT_PERSON;
  196.                  pstmt.setLong(1,person_id);
  197.                  pstmt.setString(2, first_name);
  198.                  pstmt.setString(3, last_name);
  199.                  pstmt.setDate(4, born_date);
  200.                  System.out.println("===== Executing Insert =========================================");
  201.                  System.out.println(pstmt.toString());
  202.                  System.out.println("Update executed with code:" +  pstmt.executeUpdate());
  203.        }
  204.            catch(SQLException ex) {
  205.                 // handle any errors
  206.                 System.out.println("SQLException: " + ex.getMessage());
  207.                 System.out.println("SQLState: " + ex.getSQLState());
  208.                 System.out.println("VendorError: " + ex.getErrorCode());        
  209.                 System.exit(-1);
  210.            }
  211.    }
  212.    
  213.    /**
  214.     * @param query
  215.     * This method is currently not used. It demonstrates, given a query, how we can read meta information about tables
  216.     * in the query from the data dictionary.  
  217.     */
  218.    private void getColumnNamesAndTypes(String query)
  219.    {
  220.        ResultSet rs = null;
  221.        try {
  222.            Statement stmt = con.createStatement();              // Create a Statement object
  223.            rs = stmt.executeQuery(query);
  224.            ResultSetMetaData rsmtadta = rs.getMetaData();      // Create a ResultSetMetaData object  
  225.            int colCount = rsmtadta.getColumnCount();                                  
  226.            for (int i=1; i<= colCount; i++)
  227.            {                                          
  228.                String colName = rsmtadta.getColumnName(i);    // Get column name
  229.                String colType = rsmtadta.getColumnTypeName(i);
  230.                System.out.println("Column = " + colName + " is data type " + colType);  // Print the column value
  231.            }
  232.            stmt.close();
  233.        }
  234.        catch(SQLException ex) {
  235.         // handle any errors
  236.         System.out.println("SQLException: " + ex.getMessage());
  237.         System.out.println("SQLState: " + ex.getSQLState());
  238.         System.out.println("VendorError: " + ex.getErrorCode());        
  239.         System.exit(-1);
  240.        }
  241.    }
  242.  
  243. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement