Commit b185265c authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.
Browse files

Initial commit

parents
Loading
Loading
Loading
Loading
+194 −0
Changes for MYSQL/CHAPTER1/FifthExample.java: 194 added lines, 0 removed lines.
Original line number Diff line number Diff line
import java.io.*;
import java.sql.*;
import java.util.Properties;
import java.text.*;
import java.lang.Math.*;

public class FifthExample{

   private static Connection        con;

   private static Connection DBConnect(String cnx,
                                       String username,
                                       String password) throws Exception {
        Connection mycon = null;

        try {
             // Establish Connection to the database
             if (username != null) {
                 mycon = DriverManager.getConnection(cnx, username, password);
             } else {
                 mycon = DriverManager.getConnection(cnx);
             }
        } catch (Exception e) {
             System.err.print("Warning : ");
             System.err.println(e.getMessage());
        }
        return mycon;
       }

  
    private static Properties LoadProp() throws Exception {
        Properties prop = new Properties();
        try {
             FileInputStream fis = new
                            FileInputStream("database.properties");
             prop.load(fis);
        } catch (Exception e) {
             System.err.print("Warning : ");
             System.err.println(e.getMessage());
        }
        return prop;
    }

    public static void main(String args[]) throws Exception {
        String           cnx;
        String           username = null;
        String           password = null;
        String           driver;
        String           queryString = "";
        Properties       myprop;
        FileReader       filereader;
        int              i;
        int              j;
        int              k;
        int              dummy;
        String           somedate = "00/00/0000";
        String           valuationdate = "00/00/0000";
        int              areaid;
        long             start;
        long             stop;

        myprop = LoadProp();
        if (((driver = System.getProperty("DRIVER")) == null)
            && ((driver = myprop.getProperty("DRIVER")) == null)) {
            System.err.println("Undefined JDBC driver (DRIVER parameter)");
            System.exit(1);
        }
        Class.forName(driver).newInstance();
        if (((cnx = System.getProperty("CONNECT")) == null)
            && ((cnx = myprop.getProperty("CONNECT")) == null)) {
            System.err.println("Undefined connection string " +
                               "(CONNECT parameter)");
            System.exit(1);
        }
        // Username / Password may be passed in CONNECT
        if ((username = System.getProperty("USERNAME")) == null) {
            username = myprop.getProperty("USERNAME");
        }
        if (username != null) {
            if (((password = System.getProperty("PASSWORD")) == null)
                && ((password = myprop.getProperty("PASSWORD")) == null)) {
                System.err.println("Both username and password "
                                   + "must be set");
                System.exit(1);
            }
        }

      con = DBConnect(cnx, username, password);
      // We arbitrarily set three values:
      //     * One "areaid"
      //     * One date for fetching transactions after a given time
      //     * One valuation date for currency conversion 
      //
      areaid = 7;
      // Get a particular date
      try {
           Statement st = con.createStatement();
           String sqltext = "select txdate from transactions where txid=12345"; 
           ResultSet rs = st.executeQuery(sqltext);
           if (rs.next()) {
              somedate = rs.getString(1);
           }
           System.out.println("areaid=" + Integer.toString(areaid) + ", somedate=" + somedate);
           sqltext = "select max(rate_date) from currency_rates";
           rs = st.executeQuery(sqltext);
           if (rs.next()) {
              valuationdate = rs.getString(1);
           }
           System.out.println("valuationdate=" + valuationdate);
           rs.close();
           st.close();
      } catch(SQLException ex){
            System.err.println("==> SQLException: ");
            while (ex != null) {
                System.out.println("Message:   " + ex.getMessage ());
                System.out.println("SQLState:  " + ex.getSQLState ());
                System.out.println("ErrorCode: " + ex.getErrorCode ());
                ex = ex.getNextException();
                System.out.println("");
            }
      }
      // Clean-up the check_log table 
      Statement stmt = con.createStatement();
      stmt.executeUpdate("truncate table check_log");
      stmt.close();
      // Now the real process
      start = System.currentTimeMillis();
      try {
           PreparedStatement st = con.prepareStatement("insert into check_log(txid,conv_amount)"
                                                      + "select x.txid,x.amount*y.rate"
                                                      + " from(select a.txid,"
                                                      + "             a.amount,"
                                                      + "             a.curr"
                                                      + "      from transactions a"
                                                      + "      where a.accountid in"
                                                      + "             (select accountid"
                                                      + "              from area_accounts"
                                                      + "              where areaid = ?)"
                                                      + "        and a.txdate >= date_sub(?, interval 30 day)"
                                                      + "        and exists (select 1"
                                                      + "                    from thresholds c"
                                                      + "                    where c.iso = a.curr"
                                                      + "                      and a.amount >= c.threshold)) x,"
                                                      + "     currency_rates y"
                                                      + "  where y.iso = x.curr"
                                                      + "  and y.rate_date=?");

           // Turn autocommit off
           con.setAutoCommit(false); 
           st.setInt(1, areaid);
           st.setString(2, somedate);
           st.setString(3, valuationdate);
           // Wham bam
           st.executeUpdate();
           st.close();
           con.commit();
      } catch(SQLException ex){
            con.rollback();
            System.err.println("==> SQLException: ");
            while (ex != null) {
                System.out.println("Message:   " + ex.getMessage ());
                System.out.println("SQLState:  " + ex.getSQLState ());
                System.out.println("ErrorCode: " + ex.getErrorCode ());
                ex = ex.getNextException();
                System.out.println("");
            }
      }
      stop = System.currentTimeMillis();
      // Last check
      try {
           Statement st = con.createStatement();
           String sqltext = "select count(*), min(txid), max(txid) from check_log"; 
           ResultSet rs = st.executeQuery(sqltext);
           if (rs.next()) {
              System.out.println("Logged transactions = " + Integer.toString(rs.getInt(1)) +
                                 ", from " + Long.toString(rs.getLong(2)) +
                                 " to " + Long.toString(rs.getLong(3)));
           }
           rs.close();
           st.close();
      } catch(SQLException ex){
            System.err.println("==> SQLException: ");
            while (ex != null) {
                System.out.println("Message:   " + ex.getMessage ());
                System.out.println("SQLState:  " + ex.getSQLState ());
                System.out.println("ErrorCode: " + ex.getErrorCode ());
                ex = ex.getNextException();
                System.out.println("");
            }
      }
      System.out.println("Elapsed (ms)\t" + (stop - start));
      con.close();
    }
}
+255 −0
Changes for MYSQL/CHAPTER1/FirstExample.java: 255 added lines, 0 removed lines.
Original line number Diff line number Diff line
import java.io.*;
import java.sql.*;
import java.util.Properties;
import java.text.*;
import java.lang.Math.*;

public class FirstExample{

   private static Connection        con;

   private static Connection DBConnect(String cnx,
                                       String username,
                                       String password) throws Exception {
        Connection mycon = null;

        try {
             // Establish Connection to the database
             if (username != null) {
                 mycon = DriverManager.getConnection(cnx, username, password);
             } else {
                 mycon = DriverManager.getConnection(cnx);
             }
        } catch (Exception e) {
             System.err.print("Warning : ");
             System.err.println(e.getMessage());
        }
        return mycon;
       }

  
    private static Properties LoadProp() throws Exception {
        Properties prop = new Properties();
        try {
             FileInputStream fis = new
                            FileInputStream("database.properties");
             prop.load(fis);
        } catch (Exception e) {
             System.err.print("Warning : ");
             System.err.println(e.getMessage());
        }
        return prop;
    }

    private static boolean AboveThreshold(float amount, String iso) throws Exception {
        PreparedStatement thresholdstmt = con.prepareStatement("select threshold"
                                                              + " from thresholds"
                                                              + " where iso=?");
        ResultSet         rs;

        thresholdstmt.setString(1, iso);
        rs = thresholdstmt.executeQuery();
        if (rs.next()) {
           if (amount >= rs.getFloat(1)){
              rs.close();
              thresholdstmt.close();
              return true;
           } else {
              rs.close();
              thresholdstmt.close();
              return false;
           }          
        } else {   // not found - assume no problem
          rs.close();
          thresholdstmt.close();
          return false;
        }
    }

    private static float Convert(float amount, String iso, String valuationdate) throws Exception {
        PreparedStatement conversionstmt = con.prepareStatement("select ? * rate"
                                                               + " from currency_rates"
                                                               + " where iso = ?"
                                                               + " and rate_date = ?");
        ResultSet         rs;
        float             val = (float)0.0;

        conversionstmt.setFloat(1, amount);
        conversionstmt.setString(2, iso);
        conversionstmt.setString(3, valuationdate);
        rs = conversionstmt.executeQuery();
        if (rs.next()) {
           val = rs.getFloat(1);
        }
        rs.close();
        conversionstmt.close();
        return val;
    }

    public static void main(String args[]) throws Exception {
        String           cnx;
        String           username = null;
        String           password = null;
        String           driver;
        String           queryString = "";
        Properties       myprop;
        FileReader       filereader;
        int              i;
        int              j;
        int              k;
        int              dummy;
        String           somedate = "00/00/0000";
        String           valuationdate = "00/00/0000";
        int              areaid;
        long             start;
        long             stop;

        myprop = LoadProp();
        if (((driver = System.getProperty("DRIVER")) == null)
            && ((driver = myprop.getProperty("DRIVER")) == null)) {
            System.err.println("Undefined JDBC driver (DRIVER parameter)");
            System.exit(1);
        }
        Class.forName(driver).newInstance();
        if (((cnx = System.getProperty("CONNECT")) == null)
            && ((cnx = myprop.getProperty("CONNECT")) == null)) {
            System.err.println("Undefined connection string " +
                               "(CONNECT parameter)");
            System.exit(1);
        }
        // Username / Password may be passed in CONNECT
        if ((username = System.getProperty("USERNAME")) == null) {
            username = myprop.getProperty("USERNAME");
        }
        if (username != null) {
            if (((password = System.getProperty("PASSWORD")) == null)
                && ((password = myprop.getProperty("PASSWORD")) == null)) {
                System.err.println("Both username and password "
                                   + "must be set");
                System.exit(1);
            }
        }

      con = DBConnect(cnx, username, password);
      // We arbitrarily set three values:
      //     * One "areaid"
      //     * One date for fetching transactions after a given time
      //     * One valuation date for currency conversion 
      //
      areaid = 7;
      // Get a particular date
      try {
           Statement st = con.createStatement();
           String sqltext = "select txdate from transactions where txid=12345"; 
           ResultSet rs = st.executeQuery(sqltext);
           if (rs.next()) {
              somedate = rs.getString(1);
           }
           System.out.println("areaid=" + Integer.toString(areaid) + ", somedate=" + somedate);
           sqltext = "select max(rate_date) from currency_rates";
           rs = st.executeQuery(sqltext);
           if (rs.next()) {
              valuationdate = rs.getString(1);
           }
           System.out.println("valuationdate=" + valuationdate);
           rs.close();
           st.close();
      } catch(SQLException ex){
            System.err.println("==> SQLException: ");
            while (ex != null) {
                System.out.println("Message:   " + ex.getMessage ());
                System.out.println("SQLState:  " + ex.getSQLState ());
                System.out.println("ErrorCode: " + ex.getErrorCode ());
                ex = ex.getNextException();
                System.out.println("");
            }
      }
      // Clean-up the check_log table 
      Statement stmt = con.createStatement();
      stmt.executeUpdate("truncate table check_log");
      stmt.close();
      // Now the real process
      start = System.currentTimeMillis();
      try {
           long    txid;
           long    accountid;
           float   amount;
           String  curr;
           float   conv_amount;

           PreparedStatement st1 = con.prepareStatement("select accountid"
                                                        + " from area_accounts"
                                                        + " where areaid = ?");
           ResultSet         rs1;
           PreparedStatement st2 = con.prepareStatement("select txid,amount,curr"
                                                        + " from transactions"
                                                        + " where accountid=?"
                                                        + " and txdate >= date_sub(?, interval 30 day)"
                                                        + " order by txdate");
           ResultSet         rs2;
           PreparedStatement st3 = con.prepareStatement("insert into check_log(txid,"
                                                        + " conv_amount)"
                                                        + " values(?,?)");
           
           st1.setInt(1, areaid);
           rs1 = st1.executeQuery();
           while (rs1.next()) {
              accountid = rs1.getLong(1);
              st2.setLong(1, accountid);
              st2.setString(2, somedate);
              rs2 = st2.executeQuery();
              while (rs2.next()) {
                 txid = rs2.getLong(1);
                 amount = rs2.getFloat(2);
                 curr = rs2.getString(3);
                 if (AboveThreshold(amount, curr)) {
                    // Convert
                    conv_amount = Convert(amount, curr, valuationdate);
                    st3.setLong(1, txid);
                    st3.setFloat(2, conv_amount);
                    dummy = st3.executeUpdate();
                 }
              }
              rs2.close();
           }
           rs1.close();
           st3.close();
           st2.close();
           st1.close();
      } catch(SQLException ex){
            System.err.println("==> SQLException: ");
            while (ex != null) {
                System.out.println("Message:   " + ex.getMessage ());
                System.out.println("SQLState:  " + ex.getSQLState ());
                System.out.println("ErrorCode: " + ex.getErrorCode ());
                ex = ex.getNextException();
                System.out.println("");
            }
      }
      stop = System.currentTimeMillis();
      // Last check
      try {
           Statement st = con.createStatement();
           String sqltext = "select count(*), min(txid), max(txid) from check_log"; 
           ResultSet rs = st.executeQuery(sqltext);
           if (rs.next()) {
              System.out.println("Logged transactions = " + Integer.toString(rs.getInt(1)) +
                                 ", from " + Long.toString(rs.getLong(2)) +
                                 " to " + Long.toString(rs.getLong(3)));
           }
           rs.close();
           st.close();
      } catch(SQLException ex){
            System.err.println("==> SQLException: ");
            while (ex != null) {
                System.out.println("Message:   " + ex.getMessage ());
                System.out.println("SQLState:  " + ex.getSQLState ());
                System.out.println("ErrorCode: " + ex.getErrorCode ());
                ex = ex.getNextException();
                System.out.println("");
            }
      }
      System.out.println("Elapsed (ms)\t" + (stop - start));
      con.close();
    }
}
+267 −0

File added.

Preview size limit exceeded, changes collapsed.

+254 −0

File added.

Preview size limit exceeded, changes collapsed.

+258 −0

File added.

Preview size limit exceeded, changes collapsed.

Loading