-
Notifications
You must be signed in to change notification settings - Fork 0
/
BuyStock.java
95 lines (77 loc) · 3.03 KB
/
BuyStock.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import java.sql.*;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class BuyStock {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/LiteGroww";
// Database credentials
static final String USER = "root";
static final String PASS = "rikbithi";
public static void render(String un, String PAN){
System.out.print("\033[H\033[2J");
System.out.flush();
System.out.println("----- WELCOME TO LITEGROWW -----");
System.out.println();
System.out.println("Welcome, "+un);
Scanner sc = new Scanner(System.in);
System.out.print("Enter ticker of stock to buy: ");
String stock = sc.nextLine();
System.out.print("Enter number of shares to be bought: ");
int num_shares = sc.nextInt();
System.out.print("Enter buy price: ");
double buy_price = sc.nextDouble();
Connection conn = null;
Statement stmt = null;
try{
//STEP 1: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 2: Open a connection
//System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
stmt = conn.createStatement();
String sql;
sql = "select * from Stock where TKR = \'"+stock+"\';";
//STEP 4: Execute query
ResultSet rs = stmt.executeQuery(sql);
//STEP 5: Extract data from result set
while(rs.next()){
double curval = rs.getDouble("CurValue");
if(buy_price < curval){
System.out.println("trying to buy at price lower than current value, quitting");
return;
}
break;
}
sql = "call buy_share ("+num_shares+", "+buy_price+", \'"+stock+"\', \'"+PAN+"\');";
stmt.executeUpdate(sql);
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
System.out.println("Successful purchase, returning to home page...");
TimeUnit.SECONDS.sleep(1);
Home.render(un, PAN);
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}
sc.close();
}
}