forked from jkaha001/CS166Project
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEmbeddedSQL.java
More file actions
Latest commit
406 lines (354 loc) · 13 KB
/
Copy pathEmbeddedSQL.java
File metadata and controls
406 lines (354 loc) · 13 KB
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
/*
* MODIFIED BY JUSTIN KAHAL AND THOMAS DESMOND
* SSID:860892022
*
* Template JAVA User Interface
* =============================
*
* Database Management Systems
* Department of Computer Science & Engineering
* University of California - Riverside
*
* Target DBMS: 'Postgres'
*
*/
//FUCK THIS TESTING
// My newest CHANGE
importjava.sql.DriverManager;
importjava.sql.Connection;
importjava.sql.Statement;
importjava.sql.ResultSet;
importjava.sql.ResultSetMetaData;
importjava.sql.SQLException;
importjava.io.File;
importjava.io.FileReader;
importjava.io.BufferedReader;
importjava.io.InputStreamReader;
/**
* This class defines a simple embedded SQL utility class that is designed to
* work with PostgreSQL JDBC drivers.
*
*/
publicclassEmbeddedSQL {
publicstaticStringcurrentUser;
// reference to physical database connection.
privateConnection_connection = null;
// handling the keyboard inputs through a BufferedReader
// This variable can be global for convenience.
staticBufferedReaderin = newBufferedReader(
newInputStreamReader(System.in));
/**
* Creates a new instance of EmbeddedSQL
*
* @param hostname the MySQL or PostgreSQL server hostname
* @param database the name of the database
* @param username the user name used to login to the database
* @param password the user login password
* @throws java.sql.SQLException when failed to make a connection.
*/
publicEmbeddedSQL (Stringdbname, Stringdbport, Stringuser, Stringpasswd) throwsSQLException {
System.out.print("Connecting to database...");
try{
// constructs the connection URL
Stringurl = "jdbc:postgresql://localhost:" + dbport + "/" + dbname;
System.out.println ("Connection URL: " + url + "\n");
// obtain a physical connection
this._connection = DriverManager.getConnection(url, user, passwd);
System.out.println("Done");
}catch (Exceptione){
System.err.println("Error - Unable to Connect to Database: " + e.getMessage() );
System.out.println("Make sure you started postgres on this machine");
System.exit(-1);
}//end catch
}//end EmbeddedSQL
/**
* Method to execute an update SQL statement. Update SQL instructions
* includes CREATE, INSERT, UPDATE, DELETE, and DROP.
*
* @param sql the input SQL string
* @throws java.sql.SQLException when update failed
*/
publicvoidexecuteUpdate (Stringsql) throwsSQLException {
// creates a statement object
Statementstmt = this._connection.createStatement ();
// issues the update instruction
stmt.executeUpdate (sql);
// close the instruction
stmt.close ();
}//end executeUpdate
publicStringexecuteLoginQuery (Stringquery) throwsSQLException{
// creates a statement objectv
Statementstmt = this._connection.createStatement ();
// issues the query instruction
ResultSetrs = stmt.executeQuery (query);
/*
** obtains the metadata object for the returned result set. The metadata
** contains row and column info.
*/
ResultSetMetaDatarsmd = rs.getMetaData ();
intnumCol = rsmd.getColumnCount ();
rs.next();
Stringresultset = rs.getString(numCol);
System.out.println(resultset);
stmt.close();
returnresultset;
// iterates through the result set and output them to standard out.
/* boolean outputHeader = true;
while (rs.next()){
if(outputHeader){
for(int i = 1; i <= numCol; i++){
System.out.print(rsmd.getColumnName(i) + "\t");
}
System.out.println();
outputHeader = false;
}
for (int i=1; i<=numCol; ++i)
System.out.print (rs.getString (i) + "\t");
System.out.println ();
++rowCount;
}//end while
stmt.close ();
return rowCount;
*/
}
/**
* Method to execute an input query SQL instruction (i.e. SELECT). This
* method issues the query to the DBMS and outputs the results to
* standard out.
*
* @param query the input query string
* @return the number of rows returned
* @throws java.sql.SQLException when failed to execute the query
*/
publicintexecuteQuery (Stringquery) throwsSQLException {
// creates a statement objectv
Statementstmt = this._connection.createStatement ();
// issues the query instruction
ResultSetrs = stmt.executeQuery (query);
/*
** obtains the metadata object for the returned result set. The metadata
** contains row and column info.
*/
ResultSetMetaDatarsmd = rs.getMetaData ();
intnumCol = rsmd.getColumnCount ();
introwCount = 0;
// iterates through the result set and output them to standard out.
booleanoutputHeader = true;
while (rs.next()){
if(outputHeader){
for(inti = 1; i <= numCol; i++){
System.out.print(rsmd.getColumnName(i) + "\t");
}
System.out.println();
outputHeader = false;
}
for (inti=1; i<=numCol; ++i)
System.out.print (rs.getString (i) + "\t");
System.out.println ();
++rowCount;
}//end while
stmt.close ();
returnrowCount;
}//end executeQuery
/**
* Method to close the physical connection if it is open.
*/
publicvoidcleanup(){
try{
if (this._connection != null){
this._connection.close ();
}//end if
}catch (SQLExceptione){
// ignored.
}//end try
}//end cleanup
/**
* The main execution method
*
* @param args the command line arguments this inclues the <mysql|pgsql> <login file>
*/
publicstaticvoidmain (String[] args) {
if (args.length != 4) {
System.err.println (
"Usage: " +
"java [-classpath <classpath>] " +
EmbeddedSQL.class.getName () +
" <dbname> <port> <user> <passwd>");
return;
}//end if
Greeting();
EmbeddedSQLesql = null;
try{
// use postgres JDBC driver.
Class.forName ("org.postgresql.Driver").newInstance ();
// instantiate the EmbeddedSQL object and creates a physical
// connection.
Stringdbname = args[0];
Stringdbport = args[1];
Stringuser = args[2];
Stringpasswd = args[3];
esql = newEmbeddedSQL (dbname, dbport, user, passwd);
booleankeepon = true;
while(keepon) {
// These are sample SQL statements
System.out.println("WELCOME! Are you an existing user?");
System.out.println("---------");
System.out.println("0. Yes I am!");
System.out.println("1. No, I need to register!");
System.out.println("9. < EXIT (Stop the program)");
switch (readChoice()){
case0: LogInQuery(esql); break;
case1: RegisterQuery(esql); break;
case9: keepon = false; break;
default : System.out.println("Unrecognized choice!"); break;
}//end switch
}//end while
}catch(Exceptione) {
System.err.println (e.getMessage ());
}finally{
// make sure to cleanup the created table and close the connection.
try{
if(esql != null) {
System.out.print("Disconnecting from database...");
esql.cleanup ();
System.out.println("Done\n\nBye !");
}//end if
}catch (Exceptione) {
// ignored.
}//end try
}//end try
}//end main
publicstaticvoidGreeting(){
System.out.println(
"\n\n*******************************************************\n" +
" User Interface \n" +
"*******************************************************\n");
}//end Greeting
/*
* Reads the users choice given from the keyboard
* @int
**/
publicstaticintreadChoice() {
intinput;
// returns only if a correct value is given.
do {
System.out.print("Please make your choice: ");
try { // read the integer, parse it and break.
input = Integer.parseInt(in.readLine());
break;
}catch (Exceptione) {
System.out.println("Your input is invalid!");
continue;
}//end try
}while (true);
returninput;
}//end readChoice
publicstaticvoidLogInQuery(EmbeddedSQLesql){
try{
System.out.println("You are trying to Login as an existing user, enter your Username (Make sure it is only 9 chars long)");
while( true ){
System.out.println("Please specify your username:");
Stringinput = in.readLine();
Stringquery = "SELECT COUNT(user_id) FROM users WHERE user_id='";
query += input + "'";
Stringoutput = esql.executeLoginQuery (query);
if( output != "1" ) {
System.out.println("Sorry, that username isn't in our records. Please try again.");
continue;
}
elseif( output == "1" ){
currentUser = input;
System.out.println("Please specify your password:");
input = in.readLine();
query = "SELECT COUNT(user_id) FROM users WHERE user_id='" + currentUser + "' AND password='" + input + "'";
Stringoutput2 = esql.executeLoginQuery(query);
if( output2 != "1" ){
System.out.println("Sorry, the username and password don't match up. Please try again.");
continue;
}
elseif( output2 == "1" ){
System.out.println("Successfully logged in!");
break;
}
}
}
//System.out.println ("total row(s): " + rowCount);
}catch(Exceptione){
System.err.println (e.getMessage ());
}
}//end QueryExample
publicstaticvoidRegisterQuery(EmbeddedSQLesql){
try{
Stringquery = "SELECT C.sid, COUNT(C.pid) FROM Suppliers S, Catalog C "
+ "WHERE C.sid=S.sid GROUP BY C.sid;";
introwCount = esql.executeQuery (query);
System.out.println ("total row(s): " + rowCount);
}catch(Exceptione){
System.err.println (e.getMessage ());
}
}//end Query1
publicstaticvoidQuery2(EmbeddedSQLesql){
try{
Stringquery = "SELECT C.sid, COUNT(C.pid) FROM Suppliers S, Catalog C "
+ "WHERE C.sid=S.sid GROUP BY C.sid HAVING COUNT(C.pid)>=3;";
introwCount = esql.executeQuery (query);
System.out.println ("total row(s): " + rowCount);
}catch(Exceptione){
System.err.println (e.getMessage ());
}
}//end Query2
publicstaticvoidQuery3(EmbeddedSQLesql){
try{
Stringquery = "SELECT sname, COUNT(C.pid) FROM Suppliers S, Catalog C "
+ "WHERE pid IN (SELECT pid FROM Parts WHERE color='Green') AND S.sid=C.sid "
+ "GROUP BY sname";
introwCount = esql.executeQuery (query);
System.out.println ("total row(s): " + rowCount);
}catch(Exceptione){
System.err.println (e.getMessage ());
}
}//end Query3
publicstaticvoidQuery4(EmbeddedSQLesql){
try{
Stringquery = "SELECT P.pname, MAX(C.cost) FROM Parts P, Catalog C "
+ "WHERE C.sid IN (SELECT temp.sid "
+ "FROM (SELECT sid, pid FROM Catalog WHERE pid IN (SELECT pid FROM Parts WHERE color='Red')) as temp, "
+ "(SELECT sid, pid FROM catalog WHERE PID IN (SELECT pid FROM Parts WHERE color='Green')) as temp2 "
+ "WHERE temp.sid = temp2.sid) "
+ "GROUP BY P.pname;";
introwCount = esql.executeQuery (query);
System.out.println ("total row(s): " + rowCount);
}catch(Exceptione){
System.err.println (e.getMessage ());
}
}//end Query4
publicstaticvoidQuery5(EmbeddedSQLesql){
try{
Stringquery = "SELECT DISTINCT pname FROM Parts "
+ "WHERE pid IN (SELECT pid FROM Catalog WHERE cost<";
System.out.print("\tEnter cost: $");
Stringinput = in.readLine();
query+=input;
query += ");";
introwCount = esql.executeQuery (query);
System.out.println ("total row(s): " + rowCount);
}catch(Exceptione){
System.err.println (e.getMessage ());
}
}//end Query5
publicstaticvoidQuery6(EmbeddedSQLesql){
try{
Stringquery = "SELECT address FROM Suppliers WHERE sid IN ("
+ "SELECT sid FROM Catalog WHERE pid IN ("
+ "SELECT pid FROM Parts WHERE pname='";
System.out.print("\tEnter name of part: ");
Stringinput = in.readLine();
query += input;
query += "'));";
introwCount = esql.executeQuery (query);
System.out.println ("total row(s): " + rowCount);
}catch(Exceptione){
System.err.println (e.getMessage ());
}
}//end Query6
}//end EmbeddedSQL