Cancellazione e Modifica da DB mysql

di il
9 risposte

Cancellazione e Modifica da DB mysql

Salve ragazzi,

Dopo aver creato un Dinamic Web Project con Eclipse che mi permettesse di inserire nome, cognome e mail di un utente e una volta inserito correttamente di visualizzare la tabella con tutti gli utenti ora vorrei aggiungere un pulsante che mi visualizzi tutti gli utenti inseriti e poi mi permetta di cancellarli o di modificane i dati

Ho creato due classi java


package modello;

// javaBean per memorizzare i dati di un ospit nel guestbook

public class GuestBean {
	
	private String firstName, lastName, email;

	   // imposta il nome dell'ospite
	   public void setFirstName( String name ) {
	      firstName = name;  
	   }
	   
	   // ottiene il nome dell'ospite
	   public String getFirstName() {
	      return firstName;  
	   }

	   // imposta il cognome dell'ospite
	   public void setLastName( String name ) {
	      lastName = name;  
	   }

	   // ottiene il cognome dell'ospite
	   public String getLastName() {
	      return lastName;  
	   }

	   // imposta l'indirizzo email dell'ospite
	   public void setEmail( String address ) {
	      email = address;
	   }

	   // ottieni l'indirizzo email dell'ospite
	   public String getEmail() {
	      return email;  
	 
	}

}



package modello;

import java.io.*;
import java.sql.*;
import java.util.*;

public class GuestDataBean {
	
	private Connection connection;
	   private Statement statement;
	   
	   // construct TitlesBean object 
	   public GuestDataBean() throws Exception {
	        
	         Class.forName("com.mysql.jdbc.Driver");

	         // connect to the database
	         connection = DriverManager.getConnection(
	            "jdbc:mysql://localhost:/GuestBean?user=root&password=password" );

	         statement = connection.createStatement();
	   }

	   // return an ArrayList of GuestBeans
	   public List getGuestList() throws SQLException {
	      List guestList = new ArrayList();

	      // obtain list of titles
	      ResultSet results = statement.executeQuery( 
	         "SELECT firstName, lastName, email FROM guests" );

	      // get row data
	      while ( results.next() ) {
	         GuestBean guest = new GuestBean();

	         guest.setFirstName( results.getString( 1 ) );
	         guest.setLastName( results.getString( 2 ) );
	         guest.setEmail( results.getString( 3 ) );

	         guestList.add( guest ); 
	      }         

	      return guestList; 
	   }
	   
	   // insert a guest in guestbook database
	   public void addGuest( GuestBean guest ) throws SQLException {
	      statement.executeUpdate( "INSERT INTO guests ( firstName, " + 
	         "lastName, email ) VALUES ( '" + guest.getFirstName() + "', '" + 
	         guest.getLastName() + "', '" + guest.getEmail() + "' )" );
	   }

	   // close statements and terminate database connection
	   protected void finalize()
	   {
	      // attempt to close database connection
	      try {
	         statement.close();
	         connection.close();
	      }

	      // process SQLException on close operation
	      catch ( SQLException sqlException ) {
	         sqlException.printStackTrace();
	      }
	   }
}
e 3 jsp in questo modo

<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- guestBookErrorPage.jsp -->

<%-- page settings --%>
<%@ page isErrorPage = "true" %>
<%@ page import = "java.util.*" %>
<%@ page import = "java.sql.*" %>

<html xmlns = "http://www.w3.org/1999/xhtml">

   <head>
      <title>Error!</title>

      <style type = "text/css">
         .bigRed {
            font-size: 2em;
            color: red; 
            font-weight: bold;
         }
      </style>
   </head>

   <body>
      <p class = "bigRed"> 

      <% // scriptlet per determinare il tipo di eccezione
         // e stampare l'inizio del messaggio di errore
         if ( exception instanceof SQLException )
      %>

            An SQLException
			
      
      <%
		  else if ( exception instanceof ClassNotFoundException )
      %>

            A ClassNotFoundException
      
      <%
         else
      %>

            An exception

      <%-- fine scriptlett per inserire dati fissi --%>

         <%-- continua output messaggio di errore --%>
         occurred while interacting with the guestbook database. 
      </p>

      <p class = "bigRed">
         The error message was:<br />
         <%= exception.getMessage() %>
      </p>

      <p class = "bigRed">Please try again later</p>
   </body>

</html>

<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- guestBookLogin.jsp -->

<%-- page settings --%>
<%@ page errorPage = "guestBookErrorPage.jsp" %>

<%-- beans used in this JSP --%>
<jsp:useBean id = "guest" scope = "page" 
   class ="modello.GuestBean" />
<jsp:useBean id = "guestData" scope = "request" 
   class = "modello.GuestDataBean" />

<html xmlns = "http://www.w3.org/1999/xhtml">

<head>
   <title>Guest Book Login</title>

   <style type = "text/css">
      body { 
         font-family: tahoma, helvetica, arial, sans-serif;
      }

      table, tr, td { 
         font-size: .9em;
         border: 3px groove;
         padding: 5px;
         background-color: #dddddd;
      }
   </style>
</head>

<body>
   <jsp:setProperty name = "guest" property = "*" />

   <% // start scriptlet

      if ( guest.getFirstName() == null || 
           guest.getLastName() == null ||
           guest.getEmail() == null ) {

   %> <%-- fine scriptlett per inserire i dati fissi--%>

         <form method = "post" action = "guestBookLogin.jsp">
            <p>Enter your first name, last name and email
               address to register in our guest book.</p>

            <table>
               <tr>
                  <td>First name</td>

                  <td>
                     <input type = "text" name = "firstName" />
                  </td>
               </tr>

               <tr>
                  <td>Last name</td>

                  <td>
                     <input type = "text" name = "lastName" />
                  </td>
               </tr>

               <tr>
                  <td>Email</td>

                  <td>
                     <input type = "text" name = "email" />
                  </td>
               </tr>

               <tr>
                  <td colspan = "2">
                     <input type = "submit" 
                        value = "Submit" />
                  </td>
               </tr>
            </table>
         </form>

   <% // continua scriptlet

      }  // end if
      else {
         guestData.addGuest( guest );

   %> <%-- end scriptlet to insert jsp:forward action --%>

         <%-- forward to display guest book contents --%>
         <jsp:forward page = "guestBookView.jsp" />

   <% // continuea scriptlet

      }  // fine else

   %> <%-- end scriptlet --%>
</body>

</html>

<?xml version = "1.0"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<!-- Fig. 25.23: guestBookView.jsp -->

<%-- page settings --%>
<%@ page errorPage = "guestBookErrorPage.jsp" %>
<%@ page import = "java.util.*" %>
<%@ page import = "modello.*" %>

<%-- GuestDataBean per ottenere la lista degli ospiti --%>
<jsp:useBean id = "guestData" scope = "request" 
   class = "modello.GuestDataBean" />

<html xmlns = "http://www.w3.org/1999/xhtml">

   <head>
      <title>Guest List</title>

      <style type = "text/css">
         body { 
            font-family: tahoma, helvetica, arial, sans-serif; 
         }

         table, tr, td, th { 
            text-align: center;
            font-size: .9em;
            border: 3px groove;
            padding: 5px;
            background-color: #dddddd;
         }
      </style>
   </head>

   <body>
      <p style = "font-size: 2em;">Guest List</p>

      <table>
         <thead>
            <tr>
               <th style = "width: 100px;">Last name</th>
               <th style = "width: 100px;">First name</th>
               <th style = "width: 200px;">Email</th>
            </tr>
         </thead>

         <tbody>

         <% // inizio scriptlet

            List guestList = guestData.getGuestList();
            Iterator guestListIterator = guestList.iterator();
            GuestBean guest;

            while ( guestListIterator.hasNext() ) {
               guest = ( GuestBean ) guestListIterator.next();

         %> <%-- fine scriptlet; inserisci dati fissi --%>
 
               <tr>
                  <td><%= guest.getLastName() %></td>

                  <td><%= guest.getFirstName() %></td>

                  <td>
                     <a href = "mailto:<%= guest.getEmail() %>">
                        <%= guest.getEmail() %></a>
                  </td>
               </tr>

         <% // continua scriptlet

            } // fine while

         %> <%-- end scriptlet --%>
         
         </tbody>
      </table>
   </body>

</html>
sapete dirmi come modificare quello che ho scritto finora affinchè faccia quello che voglio? sono alle prime armi con i DB, ci sto provando da un po' ma senza alcun successo.

9 Risposte

  • Re: Cancellazione e Modifica da DB mysql

    PRIMA di saperlo fare mediante codice Java, lo DEVI saper fare via SQL, cioe' ACCEDENDO DIRETTAMENTE AL DATABASE.

    Quindi, domanda di rito: accedendo DIRETTAMENTE AL DATABASE, come faresti?

    O forse ho capito male il problema. Boh.

    Per il resto, e' una BANALE tabellina righe/colonne.
  • Re: Cancellazione e Modifica da DB mysql

    Per la modifica useri questa istruzione:

    UPDATE guests SET LastName = "xxxxx" WHERE firstName = "yyyy";

    e cosi via per i campi che vorrei modificare

    per la cancellazione

    DELETE from guests WHERE firstName = 'XXXXX';

    ora vorrei capire come fare per introdurre un nuovo pulsante che mi stampi la lista degli utenti presenti, selezionarne uno e decidere se eliminarlo o modificarlo.

    P.s. credo che sarebbe più corretto fare la modifica e la cancellazione per id o sbaglio?
  • Re: Cancellazione e Modifica da DB mysql

    UPDATE guests SET LastName = "xxxxx" WHERE firstName = "yyyy"; 
    In questo modo aggiorni tutti gli utenti che hanno firstName = "yyyy"

    DELETE from guests WHERE firstName = 'XXXXX';
    In questo modo elimini tutti gli utenti che hanno firstName = "XXXXX"

    Non credo che tu voglia fare questo, giusto?
    Allora devi prevedere una chiave primaria univoca (PK).
  • Re: Cancellazione e Modifica da DB mysql

    gibra ha scritto:


    UPDATE guests SET LastName = "xxxxx" WHERE firstName = "yyyy"; 
    In questo modo aggiorni tutti gli utenti che hanno firstName = "yyyy"

    DELETE from guests WHERE firstName = 'XXXXX';
    In questo modo elimini tutti gli utenti che hanno firstName = "XXXXX"

    Non credo che tu voglia fare questo, giusto?
    Allora devi prevedere una chiave primaria univoca (PK).
    si infatti ci avevo pensato
  • Re: Cancellazione e Modifica da DB mysql

    Aggiorno, sperando che qualcuno mi dia una mano

    ho modificato la JSP dove visualizzo i dati del DB in questo modo, aggiungeno un pulsante modifica ed uno cancella al alto di ogni record in questo modo
    
    <?xml version = "1.0"?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
       "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
    
    <!-- guestBookView.jsp -->
    
    <%-- page settings --%>
    <%@ page errorPage = "guestBookErrorPage.jsp" %>
    <%@ page import = "java.util.*" %>
    <%@ page import = "modello.*" %>
    
    <%-- GuestDataBean per ottenere la lista degli ospiti --%>
    <jsp:useBean id = "guestData" scope = "request" 
       class = "modello.GuestDataBean" />
    
    <html xmlns = "http://www.w3.org/1999/xhtml">
    
       <head>
          <title>Guest List</title>
    
          <style type = "text/css">
             body { 
                font-family: tahoma, helvetica, arial, sans-serif; 
             }
    
             table, tr, td, th { 
                text-align: center;
                font-size: .9em;
                border: 3px groove;
                padding: 5px;
                background-color: #dddddd;
             }
          </style>
       </head>
    
       <body>
          <p style = "font-size: 2em;">Guest List</p>
    
          <table>
             <thead>
                <tr>
                   <th style = "width: 100px;">Last name</th>
                   <th style = "width: 100px;">First name</th>
                   <th style = "width: 200px;">Email</th>
                   <th style = "width: 100px;">Seleziona per modificare</th>
                   <th style = "width: 100px;">Seleziona per cancellare</th> 
                </tr>
             </thead>
    
             <tbody>
    
             <% // inizio scriptlet
    
                List guestList = guestData.getGuestList();
                Iterator guestListIterator = guestList.iterator();
                GuestBean guest;
    
                while ( guestListIterator.hasNext() ) {
                   guest = ( GuestBean ) guestListIterator.next();
    
             %> <%-- fine scriptlet; inserisci dati fissi --%>
     
                   <tr>
                      <td><%= guest.getLastName() %></td>
    
                      <td><%= guest.getFirstName() %></td>
    
                      <td>
                         <a href = "mailto:<%= guest.getEmail() %>">
                            <%= guest.getEmail() %></a>
                      </td>
                      <td>
                         <input type ="submit" value ="Modifica" />
                      </td>
                      <td>
                          <input type ="submit" value ="Cancella" />
                      </td>
                   </tr>
    
             <% // continua scriptlet
    
                } // fine while
    
             %> <%-- end scriptlet --%>
             
             </tbody>
          </table>
       </body>
    
    qualcuno sa dirmi se c'è un modo per prelevare i dati dalla tabella tramite i pulsanti e poi in base al bottone premuto modificare(in questo caso stavo pensando ad un'altra jsp che riportasse i dati del record selezionato in appositi campi di testo per poi poterlo modificare) o cancellarla.
  • Re: Cancellazione e Modifica da DB mysql

    La chiave primaria univoca (PK) qual'è?
    Non riesco a vederla...
  • Re: Cancellazione e Modifica da DB mysql

    gibra ha scritto:


    La chiave primaria univoca (PK) qual'è?
    Non riesco a vederla...
    la chiave unica è la mail.
  • Re: Cancellazione e Modifica da DB mysql

    CRTVLB ha scritto:


    gibra ha scritto:


    La chiave primaria univoca (PK) qual'è?
    Non riesco a vederla...
    la chiave unica è la mail.
    Hai pensato cosa succede quando l'utente cambia mail?

    Personalmente io non uso mai i valori dei campi, ma creo sempre un campo numerico autoincrementale generato dal motore del database e lo chiamo:
    - ID seguito dalla tipologia della tabella (es. IDCliente, IDArticolo, IDLibro, ...)
  • Re: Cancellazione e Modifica da DB mysql

    gibra ha scritto:



    Hai pensato cosa succede quando l'utente cambia mail?
    guarda sinceramente no, sto seguendo l'esempio di un libro che putroppo si ferma all'inserimento dei dati nel db tramite una form, ora io vorrei fare cancellazione e modifica ma non ho trovato nessun esempio che mi possa essere utile per il mio caso.
Devi accedere o registrarti per scrivere nel forum
9 risposte