Guest User

Untitled

a guest
May 27th, 2018
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.21 KB | None | 0 0
  1. package Main;
  2.  
  3. import java.io.File;
  4. import java.io.FileNotFoundException;
  5. import java.sql.Connection;
  6. import java.sql.DatabaseMetaData;
  7. import java.sql.Date;
  8. import java.sql.DriverManager;
  9. import java.sql.PreparedStatement;
  10. import java.sql.ResultSet;
  11. import java.sql.SQLException;
  12. import java.text.ParseException;
  13. import java.util.ArrayList;
  14. import java.util.Scanner;
  15.  
  16. import com.mysql.jdbc.Statement;
  17.  
  18.  
  19. public class Database {
  20.  
  21.     private String user = "";
  22.     private String password = "";
  23.     private String table = "";
  24.     private String url = "jdbc:mysql://localhost/stockanalysis";
  25.    
  26.     private Connection conn = null;
  27.    
  28.     public Database()
  29.     {
  30.        
  31.     }
  32.    
  33.     public Database(String inputUser, String inputPassword)
  34.     {
  35.         user = inputUser;
  36.         password = inputPassword;
  37.     }
  38.    
  39.     public Database(String inputUser, String inputPassword, String inputTable)
  40.     {
  41.         user = inputUser;
  42.         password = inputPassword;
  43.         table = inputTable;
  44.     }
  45.    
  46.     public void setUser(String inputUser)
  47.     {
  48.         user = inputUser;
  49.     }
  50.    
  51.     public void setPassword(String inputPassword)
  52.     {
  53.         password = inputPassword;
  54.     }
  55.    
  56.     public void setTable(String inputTable)
  57.     {
  58.         table = inputTable;
  59.     }
  60.    
  61.     public void establishConnection() {
  62.         try{
  63.             try{
  64.                 Class.forName("com.mysql.jdbc.Driver").newInstance();
  65.             }catch(Exception e){
  66.                 System.err.println("Can't connect to Driver");
  67.                 System.err.println(e.getMessage());
  68.             }
  69.             conn = DriverManager.getConnection(url, user, password);
  70.             System.out.println("Connected");
  71.            
  72.         }catch(Exception e){
  73.             System.err.println("Could not Connect");
  74.             System.err.println(e.getMessage());
  75.         }
  76.     }
  77.    
  78.     public void disconnect(boolean close) throws SQLException
  79.     {
  80.         if(close)
  81.         {
  82.             conn.close();
  83.             System.out.println("Disconnected");
  84.         }
  85.     }
  86.  
  87.     public void fileToDatabase(File newFile, String tableName) throws FileNotFoundException, SQLException, ParseException
  88.     {
  89.         Scanner file = new Scanner(newFile);
  90.         file.nextLine();
  91.         int totalUpdates = 0;
  92.        
  93.         while(file.hasNext())
  94.         {
  95.             String temp = file.nextLine();
  96.             String[] line = temp.split(",");
  97.            
  98.            
  99.                        
  100.             java.sql.Date date = java.sql.Date.valueOf(line[0]);
  101.             double open = Double.parseDouble(line[1]);
  102.             double high = Double.parseDouble(line[2]);
  103.             double low = Double.parseDouble(line[3]);
  104.             double close = Double.parseDouble(line[4]);
  105.             double volume = Double.parseDouble(line[5]);
  106.            
  107.             double amountChange = close - open;
  108.             double percentChange = amountChange/open*100;
  109.            
  110.             PreparedStatement pStmt = null;
  111.            
  112.             DatabaseMetaData dbm = conn.getMetaData();
  113.  
  114.             ResultSet RS = dbm.getTables(null, null, tableName, null);
  115.             if(!RS.next())
  116.             {
  117.                 System.out.println("Table not found, creating new table.");
  118.                 String makeTable = "CREATE TABLE " + tableName + "(date DATE, PRIMARY KEY(date), open FLOAT, high FLOAT, low FLOAT, close FLOAT, volume INT, amountChange FLOAT, percentChange FLOAT )";
  119.                 pStmt = conn.prepareStatement(makeTable);
  120.                 pStmt.execute();
  121.                 System.out.println("Table created!");
  122.             }
  123.            
  124.             try{
  125.                 String insert = "INSERT INTO " + tableName + "(date, open, high, low, close, volume, amountChange, percentChange) VALUES(?, ?, ?, ?, ?, ?, ?, ?)";
  126.                 pStmt = conn.prepareStatement(insert);
  127.                 pStmt.setDate(1, date);
  128.                 pStmt.setDouble(2, open);
  129.                 pStmt.setDouble(3, high);
  130.                 pStmt.setDouble(4, low);
  131.                 pStmt.setDouble(5, close);
  132.                 pStmt.setDouble(6, volume);
  133.                 pStmt.setDouble(7, amountChange);
  134.                 pStmt.setDouble(8, percentChange);
  135.                 pStmt.executeUpdate();
  136.                 totalUpdates += pStmt.getUpdateCount();
  137.             }catch(Exception e){
  138.                 String x = e.getMessage();
  139.                 if(x.contains("Duplicate entry"))
  140.                 {
  141.                     continue;
  142.                 }
  143.                 else
  144.                     e.printStackTrace();
  145.             }
  146.         }
  147.        
  148.         System.out.println("Made " + totalUpdates + " updates to the database.");
  149.        
  150.         file.close();
  151.     }
  152.  
  153.     public ResultSet execute(String sqlQuery) throws SQLException
  154.     {
  155.         PreparedStatement pStmt1 = conn.prepareStatement(sqlQuery);
  156.         pStmt1.execute();
  157.        
  158.         ResultSet RS = pStmt1.getResultSet();
  159.        
  160.         return RS;
  161.     }
  162.    
  163.     public void deleteData() throws SQLException
  164.     {
  165.         PreparedStatement pStmt = conn.prepareStatement("TRUNCATE TABLE  analysisA");
  166.         pStmt.execute();
  167.     }
  168.    
  169.     public void insertIntoResultTable(String ticker, double nextDayIncrease, double nextDayIncreasePercent, double averageIncreasePercent, double nextDayDecrease, double nextDayDecreasePercent, double averageDecreasePercent) throws SQLException
  170.     {
  171.         double buyValue = nextDayIncreasePercent * averageIncreasePercent;
  172.         double sellValue = nextDayDecreasePercent * averageDecreasePercent;
  173.        
  174.        
  175.         PreparedStatement pStmt1 = conn.prepareStatement("INSERT INTO stockanalysis.analysisA SET ticker= '" + ticker + "', daysInc='" + nextDayIncrease + "', pctOfDaysInc='" + nextDayIncreasePercent + "', avgIncPct='" + averageIncreasePercent +
  176.                 "', daysDec='" + nextDayDecrease + "',pctOfDaysDec='" + nextDayDecreasePercent + "',avgDecPct='" + averageDecreasePercent + "',buyValue='" + buyValue + "',sellValue='" + sellValue + "';");
  177.         pStmt1.execute();
  178.        
  179.         pStmt1.close();
  180.     }
  181.    
  182.     public Date[] getDateData(String ticker) throws SQLException
  183.     {
  184.         PreparedStatement pStmt = conn.prepareStatement("SELECT date FROM " + ticker);
  185.         pStmt.executeQuery();
  186.         ResultSet RS = pStmt.getResultSet();
  187.         ArrayList<Date> dates = new ArrayList<Date>();
  188.         while(RS.next())
  189.         {
  190.             dates.add(RS.getDate(1));
  191.         }
  192.         Date[] returnDates = new Date[dates.size()];
  193.        
  194.         for(int x = 0; x < returnDates.length; x++)
  195.             returnDates[x] = dates.get(x);
  196.        
  197.         RS.close();
  198.        
  199.         return returnDates;
  200.     }
  201.    
  202.     public double[] getCloseValue(String ticker) throws SQLException
  203.     {
  204.         PreparedStatement pStmt = conn.prepareStatement("SELECT close FROM " + ticker);
  205.         pStmt.executeQuery();
  206.         ResultSet RS = pStmt.getResultSet();
  207.        
  208.         ArrayList<Double> close = new ArrayList<Double>();
  209.         while(RS.next())
  210.             close.add(RS.getDouble(1));
  211.         double[] returnClose = new double[close.size()];
  212.        
  213.         for(int x = 0; x < returnClose.length; x++)
  214.             returnClose[x] = close.get(x);
  215.        
  216.         RS.close();
  217.        
  218.         return returnClose;
  219.     }
  220.  
  221.    
  222.     public double[] getChanges(Date date, String tickerMaster) throws SQLException
  223.     {
  224.         PreparedStatement pStmt = conn.prepareStatement("SELECT percentChange FROM " + tickerMaster + " WHERE date > '" + date + "' ORDER BY date ASC");
  225.         ResultSet RS = pStmt.executeQuery();
  226.         RS.first();
  227.         ArrayList<Double> doubleList = new ArrayList<Double>();
  228.         while(RS.next())
  229.             doubleList.add(RS.getDouble("percentChange"));
  230.        
  231.         double[] newChange = new double[doubleList.size()];
  232.        
  233.        
  234.         for(int x = 0; x < newChange.length; x++)
  235.         {
  236.             newChange[x] = doubleList.get(x);
  237.         }
  238.        
  239.         return newChange;
  240.     }
  241.    
  242.     public Date[] getDate(Date date, String tickerMaster) throws SQLException {
  243.         PreparedStatement pStmt = conn.prepareStatement("SELECT date FROM " + tickerMaster + " WHERE date > '" + date + "' ORDER BY date ASC");
  244.         ResultSet RS = pStmt.executeQuery();
  245.         RS.first();
  246.         ArrayList<Date> dateList = new ArrayList<Date>();
  247.         while(RS.next())
  248.             dateList.add(RS.getDate("date"));
  249.        
  250.         Date[] newDate = new Date[dateList.size()];
  251.        
  252.         for(int x = 0; x < newDate.length; x++)
  253.         {
  254.             newDate[x] = dateList.get(x);
  255.         }
  256.         return newDate;
  257.        
  258.     }
  259.    
  260. }
Add Comment
Please, Sign In to add comment