Advertisement
Guest User

Untitled

a guest
May 18th, 2017
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.74 KB | None | 0 0
  1. // to compile this program you need to include hb15.zip
  2. // in the CLASSPATH environment variable
  3.  
  4. // We need to import the java.sql package to use JDBC
  5. import java.security.Policy.Parameters;
  6. import java.sql.*;
  7.  
  8. // for reading from the command line
  9. import java.io.*;
  10.  
  11. // for the login window
  12. import javax.swing.*;
  13. import java.awt.*;
  14. import java.awt.event.*;
  15.  
  16. // for Format.printf() and Parameters.add()
  17. import com.braju.format.*;
  18. /* CON */
  19.  
  20. /*
  21. * This class implements a graphical login window and a simple text
  22. * interface for interacting with the branch table
  23. */
  24. public class branch implements ActionListener
  25. {
  26. // command line reader Creates an InputStreamReader that uses the default charset. in, the "standard" input stream, already open and ready to supply input data, ie keyboard input.
  27. private BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
  28. // BufferedReader reads text from a character-input stream, buffering characters so as to provide for the efficient reading of chars, arrays, lines.
  29. // Buffer size may be specified, or a default size (large enough for most purposes) is used.
  30. // Each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. Advisable to swap a BufferedReader around any Reader whose read[] operations may be costly.
  31.  
  32.  
  33. /* - A connection (session) with a specific database. SQL statements are executed and results are returned within the context of a connection.
  34. - A Connection object's databse is able to provide info describing its tables, SQL grammar, procedures, etc, obtained with the getMetaData method.
  35. - When configuring Connection, JDBC apps should use the appropriate Connection method such as setAutoCommit or setTransactionIsolation.
  36. - Apps should not invoke SQL commands directly to change the connecction's config when there is a JDB method already available.
  37. - By default a Connection object is in auto-commit mode, which means that it automatically commits changes after executing each statement.
  38. - If auto-commit mode has been disabled, the method "commit" must be called explicitly in order to commit changes, or else changes will not be saved.
  39.  
  40. */private Connection con;
  41.  
  42.  
  43. // user is allowed 3 login attempts
  44. private int loginAttempts = 0;
  45.  
  46. // components of the login window
  47. // JTextField is a lightweight component that allows the editing of a single line of text.
  48. private JTextField usernameField;
  49. private JPasswordField passwordField;
  50. private JFrame mainFrame;
  51.  
  52.  
  53. /*
  54. * constructs login window and loads JDBC driver
  55. */
  56. public branch()
  57. {
  58. mainFrame = new JFrame("User Login");
  59.  
  60. JLabel usernameLabel = new JLabel("Enter username: ");
  61. JLabel passwordLabel = new JLabel("Enter password: ");
  62.  
  63. usernameField = new JTextField(10);
  64. passwordField = new JPasswordField(10);
  65. passwordField.setEchoChar('*');
  66.  
  67. JButton loginButton = new JButton("Log In");
  68.  
  69. JPanel contentPane = new JPanel();
  70. mainFrame.setContentPane(contentPane);
  71.  
  72.  
  73. // layout components using the GridBag layout manager
  74.  
  75. GridBagLayout gb = new GridBagLayout();
  76. GridBagConstraints c = new GridBagConstraints();
  77.  
  78. contentPane.setLayout(gb);
  79. contentPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
  80.  
  81. // place the username label
  82. c.gridwidth = GridBagConstraints.RELATIVE;
  83. c.insets = new Insets(10, 10, 5, 0);
  84. gb.setConstraints(usernameLabel, c);
  85. contentPane.add(usernameLabel);
  86.  
  87. // place the text field for the username
  88. c.gridwidth = GridBagConstraints.REMAINDER;
  89. c.insets = new Insets(10, 0, 5, 10);
  90. gb.setConstraints(usernameField, c);
  91. contentPane.add(usernameField);
  92.  
  93. // place password label
  94. c.gridwidth = GridBagConstraints.RELATIVE;
  95. c.insets = new Insets(0, 10, 10, 0);
  96. gb.setConstraints(passwordLabel, c);
  97. contentPane.add(passwordLabel);
  98.  
  99. // place the password field
  100. c.gridwidth = GridBagConstraints.REMAINDER;
  101. c.insets = new Insets(0, 0, 10, 10);
  102. gb.setConstraints(passwordField, c);
  103. contentPane.add(passwordField);
  104.  
  105. // place the login button
  106. c.gridwidth = GridBagConstraints.REMAINDER;
  107. c.insets = new Insets(5, 10, 10, 10);
  108. c.anchor = GridBagConstraints.CENTER;
  109. gb.setConstraints(loginButton, c);
  110. contentPane.add(loginButton);
  111.  
  112. // register password field and OK button with action event handler
  113. passwordField.addActionListener(this);
  114. loginButton.addActionListener(this);
  115.  
  116. // anonymous inner class for closing the window
  117. mainFrame.addWindowListener(new WindowAdapter()
  118. {
  119. public void windowClosing(WindowEvent e)
  120. {
  121. System.exit(0);
  122. }
  123. });
  124.  
  125. // size the window to obtain a best fit for the components
  126. mainFrame.pack();
  127.  
  128. // center the frame
  129. Dimension d = mainFrame.getToolkit().getScreenSize();
  130. Rectangle r = mainFrame.getBounds();
  131. mainFrame.setLocation( (d.width - r.width)/2, (d.height - r.height)/2 );
  132.  
  133. // make the window visible
  134. mainFrame.setVisible(true);
  135.  
  136. // place the cursor in the text field for the username
  137. usernameField.requestFocus();
  138.  
  139. try
  140. {
  141. // Load the Oracle JDBC driver
  142. DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
  143. }
  144. catch (SQLException ex)
  145. {
  146. System.out.println("Message: " + ex.getMessage());
  147. System.exit(-1);
  148. }
  149. }
  150.  
  151.  
  152. /*
  153. * connects to Oracle database named ug using user supplied username and password
  154. */
  155. private boolean connect(String username, String password)
  156. {
  157. String connectURL = "jdbc:oracle:thin:@dbhost.ugrad.cs.ubc.ca:1521:ug";
  158. // url: a databse url of the form "jdbc:subprotocol:subname".
  159. try
  160. {
  161. /*The basic service for managing a set of JDBC drivers is called DriverManager.
  162. Will attempt to load the driver classes referenced in the "jdbc.drivers" system property. This allows a user to
  163. customize the JDBC Drivers used by their app.
  164. getConnection and getDrivers: must include META-INF/services/java.sql.Driver. This file contains the name of the JDBC drivers implementation of java.sql.Diver, ie to load my.sql.Driver class, the META-INF/services/java.sql.Driver file would contain:
  165. my.sql.Driver. When the method getConnection is called, the DriverManager will attempt to locate a suitable driver form amongst those loaded at initialization and those loaded explicit using the same classloader as the current applet or application.
  166. */
  167. con = DriverManager.getConnection(connectURL,username,password);
  168. // getConnection attempts to establish a connection to the given database URL. DriverManager attempts to select an appropriate driver from the set of registered JDBC drivers.
  169. // url: a databse url of the form "jdbc:subprotocol:subname".
  170. System.out.println("\nConnected to Oracle!");
  171. return true;
  172. }
  173. catch (SQLException ex)
  174. {
  175. System.out.println("Message: " + ex.getMessage());
  176. return false;
  177. }
  178. }
  179.  
  180.  
  181. /*
  182. * event handler for login window
  183. */
  184. public void actionPerformed(ActionEvent e)
  185. {
  186. if ( connect(usernameField.getText(), String.valueOf(passwordField.getPassword())) )
  187. {
  188. // if the username and password are valid,
  189. // remove the login window and display a text menu
  190. mainFrame.dispose();
  191. showMenu();
  192. }
  193. else
  194. {
  195. loginAttempts++;
  196.  
  197. if (loginAttempts >= 3)
  198. {
  199. mainFrame.dispose();
  200. System.exit(-1);
  201. }
  202. else
  203. {
  204. // clear the password
  205. passwordField.setText("");
  206. }
  207. }
  208.  
  209. }
  210.  
  211.  
  212. /*
  213. * displays simple text interface
  214. */
  215. private void showMenu()
  216. {
  217. int choice;
  218. boolean quit;
  219.  
  220. quit = false;
  221.  
  222. try
  223. {
  224. // disable auto commit mode
  225. con.setAutoCommit(false);
  226.  
  227. while (!quit)
  228. {
  229. System.out.print("\n\nPlease choose one of the following: \n");
  230. System.out.print("1. Insert branch\n");
  231. System.out.print("2. Delete branch\n");
  232. System.out.print("3. Update branch\n");
  233. System.out.print("4. Show branch\n");
  234. System.out.print("5. Quit\n>> ");
  235.  
  236. choice = Integer.parseInt(in.readLine());
  237.  
  238. System.out.println(" ");
  239.  
  240. switch(choice)
  241. {
  242. case 1: insertBranch(); break;
  243. case 2: deleteBranch(); break;
  244. case 3: updateBranch(); break;
  245. case 4: showBranch(); break;
  246. case 5: quit = true;
  247. }
  248. }
  249.  
  250. con.close();
  251. in.close();
  252. System.out.println("\nGood Bye!\n\n");
  253. System.exit(0);
  254. }
  255. catch (IOException e)
  256. {
  257. System.out.println("IOException!");
  258.  
  259. try
  260. {
  261. con.close();
  262. System.exit(-1);
  263. }
  264. catch (SQLException ex)
  265. {
  266. System.out.println("Message: " + ex.getMessage());
  267. }
  268. }
  269. catch (SQLException ex)
  270. {
  271. System.out.println("Message: " + ex.getMessage());
  272. }
  273. }
  274.  
  275.  
  276. /*
  277. * inserts a Person. Note the original function did not have any parameters; I'm unsure whether to pass these variables into
  278. * this function or just do in.readline() directly from the prompt.
  279. */
  280. private void insertPerson(int CID, String Name, String PhoneNum, String DOB, String Password, String Email, int isAdmin)
  281. {
  282.  
  283. PreparedStatement ps;
  284. /*PreparedStatement is an object that represents a precompiled SQL statement.
  285. * A SQL statement is precompiled and stored in "ps", which can be used to efficiently execute it couple times.
  286. * The methods setShort, setString for setting IN parameter values must specify types that are compatible with the defined SQL type of the input parameter.
  287. * I.e. if the IN parameter has SQL type INTEGER, then the method setInt should be used. If arbitrary parameter type conversions are required, the method
  288. * setObject should be used with a target SQL type.
  289. * In the following example of setting a parameter, con represents an active connection:
  290.  
  291. PreparedStatement pstmt = con.prepareStatement("UPDATE EMPLOYEES
  292. SET SALARY = ? WHERE ID = ?");
  293. pstmt.setBigDecimal(1, 153833.00)
  294. pstmt.setInt(2, 110592)
  295.  
  296.  
  297. */
  298.  
  299. try
  300. {
  301. ps = con.prepareStatement("INSERT INTO branch VALUES (?,?,?,?,?,?,?)");
  302.  
  303.  
  304. // System.out.print("\nCID: ");
  305. CID = Integer.parseInt(in.readLine()); // Since this is Integer .
  306. ps.setInt(1, CID); // This must be ps.setInt
  307.  
  308. // System.out.print("\nName: ");
  309. Name = in.readLine();
  310. ps.setString(2, Name);
  311.  
  312. // System.out.print("\nPhoneNum ");
  313. PhoneNum = in.readLine();
  314. ps.setString(3, PhoneNum);
  315.  
  316. DOB = in.readLine();
  317. ps.setString(4, DOB);
  318.  
  319. Password = in.readLine();
  320. ps.setString(5, Password);
  321.  
  322. Email = in.readLine();
  323. ps.setString(6, Email);
  324.  
  325. isAdmin = Integer.parseInt( in.readLine());
  326. ps.setInt(6, isAdmin);
  327.  
  328. ps.executeUpdate(); // Executes ps = con.prepareStatement("INSERT INTO branch VALUES (?,?,?,?,?,?,?)");
  329. // Executes the SQL statement in this PreparedStatement object, which must be an SQL Data Manipulation Language (DML) statement, such as INSERT, UPDATE or DELETE; or an SQL statement that returns nothing, such as a DDL statement.
  330.  
  331. // Returns:
  332. // either (1) the row count for SQL Data Manipulation Language (DML) statements or (2) 0 for SQL statements that return nothing
  333. // ps.ex
  334.  
  335. // commit work
  336. con.commit();
  337.  
  338. ps.close();
  339. }
  340. catch (IOException e)
  341. {
  342. System.out.println("IOException!");
  343. }
  344. catch (SQLException ex)
  345. {
  346. System.out.println("Message: " + ex.getMessage());
  347. try
  348. {
  349. // undo the insert
  350. con.rollback();
  351.  
  352. }
  353. catch (SQLException ex2)
  354. {
  355. System.out.println("Message: " + ex2.getMessage());
  356. System.exit(-1);
  357. }
  358. }
  359. }
  360.  
  361.  
  362. /*
  363. * deletes a branch
  364. */
  365. private void deleteBranch()
  366. {
  367. int bid;
  368. PreparedStatement ps;
  369.  
  370. try
  371. {
  372. ps = con.prepareStatement("DELETE FROM branch WHERE branch_id = ?");
  373.  
  374. System.out.print("\nBranch ID: ");
  375. bid = Integer.parseInt(in.readLine());
  376. ps.setInt(1, bid);
  377.  
  378. int rowCount = ps.executeUpdate();
  379.  
  380. if (rowCount == 0)
  381. {
  382. System.out.println("\nBranch " + bid + " does not exist!");
  383. }
  384.  
  385. con.commit();
  386.  
  387. ps.close();
  388. }
  389. catch (IOException e)
  390. {
  391. System.out.println("IOException!");
  392. }
  393. catch (SQLException ex)
  394. {
  395. System.out.println("Message: " + ex.getMessage());
  396.  
  397. try
  398. {
  399. con.rollback();
  400. }
  401. catch (SQLException ex2)
  402. {
  403. System.out.println("Message: " + ex2.getMessage());
  404. System.exit(-1);
  405. }
  406. }
  407. }
  408.  
  409.  
  410. /*
  411. * updates the name of a branch
  412. */
  413. private void updateBranch()
  414. {
  415. int bid;
  416. String bname;
  417. PreparedStatement ps;
  418.  
  419. try
  420. {
  421. ps = con.prepareStatement("UPDATE branch SET branch_name = ? WHERE branch_id = ?");
  422.  
  423. System.out.print("\nBranch ID: ");
  424. bid = Integer.parseInt(in.readLine());
  425. ps.setInt(2, bid);
  426.  
  427. System.out.print("\nBranch Name: ");
  428. bname = in.readLine();
  429. ps.setString(1, bname);
  430.  
  431. int rowCount = ps.executeUpdate();
  432. if (rowCount == 0)
  433. {
  434. System.out.println("\nBranch " + bid + " does not exist!");
  435. }
  436.  
  437. con.commit();
  438.  
  439. ps.close();
  440. }
  441. catch (IOException e)
  442. {
  443. System.out.println("IOException!");
  444. }
  445. catch (SQLException ex)
  446. {
  447. System.out.println("Message: " + ex.getMessage());
  448.  
  449. try
  450. {
  451. con.rollback();
  452. }
  453. catch (SQLException ex2)
  454. {
  455. System.out.println("Message: " + ex2.getMessage());
  456. System.exit(-1);
  457. }
  458. }
  459. }
  460.  
  461.  
  462. /*
  463. * display information about branches
  464. */
  465. private void showBranch()
  466. {
  467. String bid;
  468. String bname;
  469. String baddr;
  470. String bcity;
  471. String bphone;
  472. Statement stmt;
  473. ResultSet rs;
  474.  
  475. try
  476. {
  477. stmt = con.createStatement();
  478. rs = stmt.executeQuery("SELECT * FROM branch");
  479.  
  480. // get info on ResultSet
  481. /* An object that can be used to get info about the types and properties of the columns in a ResultSet object.
  482. * The following code creates the ResultSet object rs, creates the ResultSetMetaData object rsmd, and uses rsmd to
  483. * find out how many columns rs has and whether the first column in rs can be used in a WHERE clause.
  484. *
  485. * ResultSet object is not updatable and has a cursor that moves forward only. Thus, you can iterate through it only once and
  486. * only from the first row to the last row.
  487. */
  488. ResultSetMetaData rsmd = rs.getMetaData();
  489.  
  490. // get number of columns
  491. int numCols = rsmd.getColumnCount();
  492.  
  493.  
  494. // Java doesn't support variable number of
  495. // arguments so we need to store them in a special
  496. // Parameters structure. To add arguments to a Parameters
  497. // object use the add() method,
  498. // e.g. p.add(parameter1).add(parameter2).add(parameter3). . .
  499. Parameters p = new Parameters();
  500.  
  501. // display column names;
  502. for (int i = 0; i < numCols; i++)
  503. {
  504. // get column name and print it
  505.  
  506. // The Format class provides the static printf() method
  507. // which behaves exactly like the printf() in
  508. // the C programming language. So for the line below
  509. // the text will be left aligned; it will also have a
  510. // minimum and maximum width of 15 characters.
  511. Format.printf("%-15.15s", p.add(rsmd.getColumnName(i+1)));
  512. }
  513.  
  514. System.out.println(" ");
  515.  
  516. while(rs.next())
  517. {
  518. // for display purposes get everything from Oracle
  519. // as a string
  520.  
  521. // simplified output formatting; truncation may occur
  522.  
  523. bid = rs.getString("branch_id");
  524. Format.printf("%-15.15s", p.add(bid));
  525.  
  526. bname = rs.getString("branch_name");
  527. Format.printf("%-15.15s", p.add(bname));
  528.  
  529. baddr = rs.getString("branch_addr");
  530. if (rs.wasNull())
  531. {
  532. Format.printf("%-15.15s", p.add(" "));
  533. }
  534. else
  535. {
  536. Format.printf("%-15.15s", p.add(baddr));
  537. }
  538.  
  539. bcity = rs.getString("branch_city");
  540. Format.printf("%-15.15s", p.add(bcity));
  541.  
  542. bphone = rs.getString("branch_phone");
  543. if (rs.wasNull())
  544. {
  545. Format.printf("%-15.15s\n", p.add(" "));
  546. }
  547. else
  548. {
  549. Format.printf("%-15.15s\n", p.add(bphone));
  550. }
  551. }
  552.  
  553. // close the statement;
  554. // the ResultSet will also be closed
  555. stmt.close();
  556. }
  557. catch (SQLException ex)
  558. {
  559. System.out.println("Message: " + ex.getMessage());
  560. }
  561. }
  562.  
  563.  
  564. public static void main(String args[])
  565. {
  566. branch b = new branch();
  567. }
  568. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement