Podstrony
- Strona startowa
- Bruce Morris Adventure Guide Florida Keys & Everglades National Park (2005)
- The Career Survival Guide Dealing with Office Politics Brian OÂ’Connell
- (Ross Enamait) The Underground Guide To Warrior Fitness
- Novell Netware 5 Advanced Admin Instructor guide
- Cole Courtney Beautifully Broken. Tom 3. Zanim miłoœć nas połšczy
- Cole Allan Bunch Chris Swiaty Wilka (SCAN dal 949)
- Cisco Press CCDA Study Guide
- Beautifully Broken. Tom 2. JeÂœli odejdziesz Cole Courtney
- Linux Network Admistrator's Guide
- Chmielewska Joanna Studnie Przodkow scr (2)
- zanotowane.pl
- doc.pisz.pl
- pdf.pisz.pl
- boszanna.htw.pl
[ Pobierz całość w formacie PDF ]
.setEditable(false);JPanel second = new JPanel();second.setLayout(new GridLayout(6,1));second.add(accountIDText);second.add(usernameText);second.add(passwordText);second.add(tsText);second.add(activeTSText);JPanel third = new JPanel();third.add(new JScrollPane(errorText));c.add(first);c.add(second);c.add(third);setSize(500,500);show();}Listing 5.3 Our application for inserting a new row.(continues)Executing a Query with No Results 95public void connectToDB() {try {connection = DriverManager.getConnection("jdbc:mysql://192.168.1.25/accounts?user=spider&password=spider");} catch(SQLException connectException) {System.out.println("unable to connect to db");System.exit(1);}}private void displaySQLErrors(SQLException e) {errorText.append("SQLException: " + e.getMessage() + "\n");errorText.append("SQLState: " + e.getSQLState() + "\n");errorText.append("VendorError: " + e.getErrorCode() + "\n");}private void init() {connectToDB();}public static void main(String[] args) {Accounts accounts = new Accounts();accounts.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {System.exit(0);}});accounts.init();accounts.buildGUI();}}Listing 5.3 Our application for inserting a new row.(continued)Figure 5.5 shows how our GUI should look when it is finished.There are a fewdifferences between the code in Listing 5.2 and that in Listing 5.3.Let s take alook.96 Using JDBC with Java Applications and AppletsFigure 5.5 Inserting a new row.The Insert Account ButtonBy far the largest change between the two applications is the addition of anInsert Account button.First, notice that the format of the button code looks agreat deal like that used for the Get Account button.The primary difference isthe database code placed in the ActionListener().The code for inserting a new row into the database requires that the actual val-ues be pulled from each of the top three JTextFields defined to hold the accountnumber, username, and password.The code will first enter a try/catch blockand obtain a Statement object.Next, the executeUpdate() method is calledusing a query string likeINSERT INTO acc_acc VALUES(account number, username, password, 0, now)The account number, username, and password are pulled from the appropriateJTextFields using the getText() method.The return value from the execution ofthe executeUpdate() method is saved and appended to a JTextArea control forerror messages.A value of 1 indicates that the insert was successful.With the new record in the database, the account number JList is out-of-datebecause it doesn t contain the new account number just inserted.This is wherea new method called loadAccounts() comes into play.Once the total number ofinserts to the database is put into the JTextArea, a call is made to theremoveAll() method of the account number JList control.This wipes out all ofthe current account numbers.Next, a call is made to loadAccounts(), whichqueries the database for all current account numbers, places them in a vector,and updates the account number JList control with all of the new accounts.Wecould have chosen to simply insert the new account number into the accountnumber list, but there might have been updates to the table that didn t comethrough the GUI.By doing the query again, we pick up all new accounts.Clearly, this is a design decision.If this GUI application is the only way newaccounts will be put into the database, then we could just add the account num-ber to the JList and not run another query of the database.Executing a Query with No Results 97As Figure 5.6 shows, a new record was added to the database with an accountnumber of 1034997.The new account number now appears in the list becauseof the re-query.Figure 5.6 Our insert was successful.Error NotificationAs we briefly mentioned in the previous section, this new version of the GUIcode includes a JTextArea designed to hold error or notification informationfor the application.Figure 5.7 shows an example of how error informationmight look like when placed in the text area.While any of the code can put textinto the text area using the append() method, all of the try/catch blocks will callthe displaySQLErrors() method to append the SQLException message, SQL-State, and error code information:private void displaySQLErrors(SQLException e) {errorText.append("SQLException: " + e.getMessage() + "\n");errorText.append("SQLState: " + e.getSQLState() + "\n");errorText.append("VendorError: " + e.getErrorCode() + "\n");}Figure 5.7 Error processing.Deleting Database RowsAnother task that can be accomplished using the updateQuery() method isremoving rows from the database.We can add the code in Listing 5.4 to the codein Listing 5.3 to produce an application that can delete rows in the database.98 Using JDBC with Java Applications and Applets//Do Delete Account ButtondeleteAccountButton = new JButton("Delete Account");deleteAccountButton.addActionListener (new ActionListener() {public void actionPerformed(ActionEvent e) {try {Statement statement = connection.createStatement();int i = statement.executeUpdate("DELETE FROM acc_acc WHERE acc_id = "+ accountNumberList.getSelectedValue());errorText.append("Deleted " + i + "rows successfully");accountNumberList.removeAll();loadAccounts();} catch(SQLException insertException) {displaySQLErrors(insertException);}}});Listing 5.4 Our Delete Account button code.The code for the Delete Account button is similar to the code for the GetAccount and Insert Account buttons.Most of the work is performed in theActionListener().To delete an account, the user selects a value from theaccount number list control and clicks on the Delete Account button.When thisoccurs, the ActionListener() is activated.The first step is to create a Statementobject and call the executeUpdate() with the query to be executed.The querylooks like this:DELETE FROM acc_acc WHERE acc_id = " +accountNumberList.getSelectedValue()This query tells the database server to find the row or rows where the acc_idcolumn has a value selected from the account number list.The executeUp-date() method executes the query and returns the total number of rows deletedfrom the database.Figure 5.8 shows the output produced when a row is deletedfrom the database.In addition to displaying the output, the code refreshes theaccount number list from the database so that the deleted account number is nolonger shown.When the code in Listing 5.4 is added to the application, the firstJPanel s GridLayout needs to be changed to 4,1 and the deleteAccountButtonneeds to be added to the panel.Here s the replacement code:JPanel first = new JPanel(new GridLayout(4,1));first.add(accountNumberListScrollPane);first.add(getAccountButton);Executing a Query with No Results 99first.add(insertAccountButton);first.add(deleteAccountButton);Figure 5.8 We've deleted a row from the database
[ Pobierz całość w formacie PDF ]