IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Langage Java Discussion :

Pas de connections à différentes classes.


Sujet :

Langage Java

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre éclairé
    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    470
    Détails du profil
    Informations personnelles :
    Localisation : Belgique

    Informations forums :
    Inscription : Janvier 2009
    Messages : 470
    Par défaut Pas de connections à différentes classes.
    Bonjour la communauté,

    Apparemment mon prg n'utilise pas as mes classe PersInfo et PersDAO et donc ma Db ne se peuple pas.

    J'ai mis des "mouchards (ex: System.out.println("PersInfo 2this "+ LastName) restent vides.
    Qu'est-ce qui empêche de mettre ma DB à jour?
    Merci de votre aide

    Habiler

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
     
    import java.awt.event.ActionListener;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.util.ArrayList;
    import javax.swing.JOptionPane;
     
     
    public class Ecran extends javax.swing.JFrame implements ActionListener {
    private Connection conn;
    private ArrayList personsList;
    int id,recordNumber,EmployeeNbr,Pourcent,DecNumber;
    String LastName,FirstName;
    PersonDAO pDAO;
     
                /**
         * Creates new form NewJFrame
         */
        public Ecran() {
                     EmployeeNbr    = 0;
                    Pourcent       = 0;
                    DecNumber      = 0;
                    Pourcent       = 0;
                    LastName       = "";
                    FirstName      = ""; 
                    id    = 0;     
            initComponents();
     
            	personsList = new ArrayList();
                    pDAO = new PersonDAO();	
     
     
    		initConn();
        }
    //****************************************************************************
          // method used to establish connection with DB
    	public void initConn()
    	{
    		try
    		{
    			// load driver
    			Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
     
                      // establishing connection
                      conn = DriverManager.getConnection("jdbc:ucanaccess://c:/Users\\hab\\Desktop\\Decisions1.accdb","","");
     
                    }
     
    		catch(Exception e)
    		{
    			System.out.println("ERREUR");
    		}
    	}
     
     
        /**
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
     
            panel1 = new java.awt.Panel();
            intEmployeeNbr = new java.awt.TextField();
            TxtLastName = new java.awt.TextField();
            TxtFirstName = new java.awt.TextField();
            LblEmployeeNbr = new javax.swing.JLabel();
            LblLastName = new javax.swing.JLabel();
            LblFirstName = new javax.swing.JLabel();
            LblDecNumber = new javax.swing.JLabel();
            intDecNumber = new java.awt.TextField();
            intPourcent = new java.awt.TextField();
            LbPourcent = new javax.swing.JLabel();
            jButton1 = new javax.swing.JButton();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
            LblEmployeeNbr.setText("Matricule :");
     
            LblLastName.setText("Nom :");
     
            LblFirstName.setText("Prénoms :");
     
            LblDecNumber.setText("N° décision :");
     
            LbPourcent.setText("Pourcentage :");
     
            jButton1.setText("jButton1");
            jButton1.addActionListener(this);
     
            javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
            panel1.setLayout(panel1Layout);
            panel1Layout.setHorizontalGroup(
                panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(panel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(panel1Layout.createSequentialGroup()
                            .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(LblEmployeeNbr, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(LblFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(LblLastName, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(TxtFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(TxtLastName, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(intEmployeeNbr, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGroup(panel1Layout.createSequentialGroup()
                            .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(LblDecNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(LbPourcent, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(intPourcent, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(intDecNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 82, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addComponent(jButton1))
                    .addContainerGap(171, Short.MAX_VALUE))
            );
            panel1Layout.setVerticalGroup(
                panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(panel1Layout.createSequentialGroup()
                    .addContainerGap()
                    .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(LblEmployeeNbr, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(intEmployeeNbr, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(TxtLastName, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(LblLastName, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(LblFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(TxtFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(LblDecNumber, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(intDecNumber, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                    .addGroup(panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(intPourcent, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(LbPourcent, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 52, Short.MAX_VALUE)
                    .addComponent(jButton1)
                    .addGap(28, 28, 28))
            );
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(36, 36, 36)
                    .addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(35, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                    .addContainerGap(26, Short.MAX_VALUE)
                    .addComponent(panel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(20, 20, 20))
            );
     
            pack();
        }
     
        // Code for dispatching events from components to event handlers.
     
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == jButton1) {
                Ecran.this.jButton1ActionPerformed(evt);
            }
        }// </editor-fold>                        
     
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
     
                      savePerson();
     
                      // clear fields
                      clear(); 
     
        }                                        
     
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(Ecran.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(Ecran.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(Ecran.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(Ecran.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
            //</editor-fold>
     
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Ecran().setVisible(true);
                }
            });
        }
     
        // Variables declaration - do not modify                     
        private javax.swing.JLabel LbPourcent;
        private javax.swing.JLabel LblDecNumber;
        private javax.swing.JLabel LblEmployeeNbr;
        private javax.swing.JLabel LblFirstName;
        private javax.swing.JLabel LblLastName;
        private java.awt.TextField TxtFirstName;
        private java.awt.TextField TxtLastName;
        private java.awt.TextField intDecNumber;
        private java.awt.TextField intEmployeeNbr;
        private java.awt.TextField intPourcent;
        private javax.swing.JButton jButton1;
        private java.awt.Panel panel1;
        // End of variables declaration                   
    //*****************************************************************************************
    	  public void savePerson()
      {  
    	/*get values from text fields*/
    	EmployeeNbr    = Integer.parseInt(intEmployeeNbr.getText());
    	LastName       = TxtLastName.getText();
    	FirstName      = TxtFirstName.getText();
            DecNumber      = Integer.parseInt(intDecNumber.getText());
            Pourcent       = Integer.parseInt(intPourcent.getText());
     
    System.out.println("Ecran 1 :" + intEmployeeNbr);       
    System.out.println("Ecran 1 :" + TxtLastName);
     
    	if(EmployeeNbr==0)
    	{
    		JOptionPane.showMessageDialog(null, "Please enter person EmployeeNbr.");
    	}else
          {
     
    	  /*create a new PersonInfo object and pass it to PersonDAO to save it*/
    	  PersonInfo person = new PersonInfo(EmployeeNbr, LastName, FirstName, DecNumber, Pourcent);
    	  pDAO.savePerson(person);
                System.out.println("Ecran 2 :" + LastName);
    	  JOptionPane.showMessageDialog(null, "Record added");
          }
      }
     
    //*******************************************************************************************************
      public void clear(){
     
    	/*clear text fields*/
    	intEmployeeNbr.setText("");
    	intDecNumber.setText("");
    	intPourcent.setText("");
            TxtLastName.setText("");
            TxtFirstName.setText("");
    	/*clear contents of arraylist*/
            recordNumber = -1;
    	personsList.clear();
    	//bForward.setEnabled(true);
    	//bBack.setEnabled(true);
      }
     
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    public class PersonInfo
    {
    	private String LastName,FirstName;
    	private int id,EmployeeNbr,DecNumber, Pourcent;
     
          // default constructor
          public PersonInfo()
          {       
     
             LastName = "";
             FirstName = "";
             System.out.println("PersInfo 2this "+ LastName);
             id = 0;
             EmployeeNbr = 0;
             DecNumber = 0;  
             Pourcent = 0;
          }
     
          // param constructor with 5 values 
    	public PersonInfo(int EmployeeNbr, int DecNumber, String LastName,String FirstName, int Pourcent)
    	{
                    this.id = id;           
                    this.EmployeeNbr = EmployeeNbr;
                    this.DecNumber = DecNumber;
    		this.LastName = LastName;
    		this.FirstName = FirstName;
                    this.Pourcent = Pourcent;
    	}
             PersonInfo(int id, int EmployeeNbr, String LastName,int DecNumber , String FirstName, int Pourcent) {
             System.out.println("PersInfo 1"+ LastName);
     
     
        }
            // param construcrtor with 4 values 
    	public PersonInfo(int EmployeeNbr, String LastName, String FirstName, int Pourcent)
    	{
                //this.DecNumber = DecNumber;
    		this.EmployeeNbr = EmployeeNbr;
    		this.LastName = LastName;
                    this.FirstName = FirstName;
    		this.Pourcent = Pourcent;
     
     
    	}
     
       PersonInfo(String LastName, String FirstName, int Pourcent) {
       }
     
        PersonInfo(int EmployeeNbr, String LastName, String FirstName, int DecNumber, int Pourcent) {
    //        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
     
          // setters
    	public void  setId(int i)
    	{
    		DecNumber = i;
     
            }
    	public void  setEmployeeNbr(int n)
    	{
    		EmployeeNbr=n;		
    	}
    	public void  setLastName(String a)
    	{
    		LastName=a;
    	}
    	public void  setPourcent(int ph)
    	{
    		Pourcent=ph;
    	}
    	public void  setFirstName(String e)
    	{
    		FirstName=e;
    	}
     
          // getters
    	public int getDecNumber( )
    	{
    		return DecNumber;
          }
     
    	public int getEmployeeNbr()
    	{
    		return EmployeeNbr;
    	}
     
    	public String getLastName()
    	{
    		return LastName;
    	}
     
    	public int getPourcent()
    	{
    		return Pourcent;
    	}
     
    	public String getFirstName()
    	{
    		return FirstName;
    	}
     
    }
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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
    import java.util.*;
    import java.sql.*;
     
    public class PersonDAO
    {      
          // arraylist used to store PersonInfo objects
    	private ArrayList personsList;
     
    	private Connection conn;
     
    //***************************************************************************
         // constructor 
    	public PersonDAO()
    	{
    		personsList = new ArrayList();
    		initConn();
    	}
     
    //****************************************************************************
          // method used to establish connection with DB
    	public void initConn()
    	{
    		try
    		{
    			// load driver
    			Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
     
                      // establishing connection
                      conn = DriverManager.getConnection("jdbc:ucanaccess://c:/Users\\hab\\Desktop\\Decisions1.accdb","","");
     
                    }
     
    		catch(Exception e)
    		{
    			System.out.println("ERREUR");
    		}
    	}
     
    //****************************************************************************
          // method used to search Person against "EmployeeNbr" provDecNumbered 
    	public ArrayList searchPerson(int n)
    	{
    		try
    		{
    			String sql = "SELECT * FROM Decisions WHERE EmployeeNbr=?";
     
    			// Create a statement
     			PreparedStatement ps = conn.prepareStatement(sql);
    			ps.setInt(1,n);
     
    			// execute the statement
    			ResultSet rs = ps.executeQuery();
     
     
                      String LastName = "";
                      String FirstName = "";
     
                      int DecNumber;
                      int Pourcent;
                      int EmployeeNbr;
    			// process resultset
    			while(rs.next())
    			{
                                    EmployeeNbr = rs.getInt("EmployeeNbr");
    				FirstName = rs.getString("FirstName");
                                    LastName = rs.getString("LastName");
                                    DecNumber = rs.getInt("DecNumber");
    				Pourcent = rs.getInt("Pourcent");
     
    				//Create a PersonInfo object
    				PersonInfo person = new PersonInfo(EmployeeNbr,LastName,FirstName,DecNumber, Pourcent);
     
    				//Add the person object to array list
    				personsList.add(person);
                                    System.out.println("EPersonDAO 1 :" + LastName);
    			}
    		}
    		catch(Exception e)
    		{
    			System.out.println(e);
    		}
     
    		return personsList;
     
    	} // end searchPerson() method
     
    //*****************************************************************************************
    	public void savePerson(PersonInfo person)
    	{
    		try
    		{
    			String sql = "INSERT INTO Decisions(EmployeeNbr, LastName, FirstName, DecNumber, Pourcent) VALUES (?,?,?,?,?) ";
     
    			// Create a statement
     			PreparedStatement ps = conn.prepareStatement(sql);
     
    			ps.setInt(1 , person.getEmployeeNbr());
                            ps.setString(2 , person.getLastName());
    			ps.setString(3 , person.getFirstName());
                            ps.setInt(4 , person.getDecNumber());
                            ps.setInt(5 , person.getPourcent());
    			// execute statement
    			ps.executeUpdate();
    		}
    		catch(Exception e)
    		{
    			System.out.println(e);
    		}
    	}
     
    //*********************************************************************************************
    	public void updatePerson(PersonInfo person)
    	{
    		try
    		{
    			String sql = "UPDATE Decisions SET EmployeeNbr = ?, LastName=? ,FirstName=?, Pourcent=? where DecNumber=?";
     
    			// Create a statement
     			PreparedStatement ps = conn.prepareStatement(sql);
     
    			ps.setInt(1 , person.getEmployeeNbr());		
    			ps.setString(2 , person.getLastName());
                            ps.setString(3 , person.getFirstName());
    			ps.setInt(4 , person.getPourcent());
     
    			// execute the statement
    			ps.executeUpdate();
    		}
    		catch(Exception e)
    		{
    			System.out.println(e);
    		}
    	}
     
    //************************************************************************************************
    	public int removePerson(String EmployeeNbr)
    	{
                // used to determine how many records deleted 
                int no = 0;
     
    		try
    		{
    			String sql = "DELETE FROM Decisions WHERE EmployeeNbr = ?";
     
    			// Create a statement
     			PreparedStatement ps = conn.prepareStatement(sql);
    			ps.setString(1, EmployeeNbr);
     
    			// execute the statement
    			no = ps.executeUpdate();
    		}
    		catch(Exception e)
    		{
    			System.out.println(e);
    		}
     
                return no;
    	}
     
    //*************************************************************************************************
    	protected void finalize()
    	{
    		try
    		{
                      if (conn != null) {
    			  conn.close();
                      }
    		}
    		catch(Exception e)
    		{
    			System.out.println(e);
    		}
    	}
     
    }// end class PersonDAO
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    Ecran 1 - EmployeeNbr :java.awt.TextField[textfield0,72,10,82x23,text=2,editable,selection=1-1]
    Ecran 1 - TxtLastName :java.awt.TextField[textfield1,72,43,82x23,text=lion,editable,selection=4-4]
    Ecran 2 :lion

  2. #2
    Rédacteur

    Homme Profil pro
    Architecte de système d'information
    Inscrit en
    Novembre 2006
    Messages
    503
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Suisse

    Informations professionnelles :
    Activité : Architecte de système d'information
    Secteur : Transports

    Informations forums :
    Inscription : Novembre 2006
    Messages : 503
    Par défaut
    Citation Envoyé par HABILER Voir le message
    Bonjour la communauté,

    Apparemment mon prg n'utilise pas as mes classe PersInfo et PersDAO et donc ma Db ne se peuple pas.

    J'ai mis des "mouchards (ex: System.out.println("PersInfo 2this "+ LastName) restent vides.
    Qu'est-ce qui empêche de mettre ma DB à jour?
    Merci de votre aide
    Je vais être honnête ... mais pas trop sympa!
    Lorsqu'on écrit ce genre d'application, il faut beaucoup plus séparer les fonctionnalités.
    Il faut être capable de tester sa base de données sans utiliser le GUI et avec des classes de test.
    Autrement dit, il faut pouvoir instancier les classes dédiées aux bases de données, qui seront utilisées plus tard par la classe Ecran et qui possèdent des méthodes de test pour, par exemple, insérer des données.
    Des "mouchards" n'apportent rien dans ce méli-mélo!

    Même la classe Ecran me gêne.
    La classe principale devrait être une classe d'application, avec un nom d'application. Cette dernière classe pourra instancier une classe Ecran voir d'autres pour la base de données.

    Pour le code, l'executeUpdate() se fait sur un Statement qui lui-même vient d'une Connexion.
    La méthode close() d'un objet de Connexion fera l'écriture dans la base de données.
    Donc close() manque, ou ne marche pas et chercher où la mettre .... reviendra à comprendre et adopter mes commentaires.

    J'ai travaillé avec Oracle, mySQL et SQLite. J'ai toujours adopter la même méthodologie.

    Je travaille beaucoup plus maintenant avec des systèmes embarqués et m'amuse avec des Raspberry Pi et des ESP8266.
    Les principes restent les mêmes, aussi pour des capteurs de mouvements, de lumière ou des relais, même en utilisant Python.
    C'est pour cela que j'adore le Raspberry Pi avec Java: des objets hardware et par exemple des objets de classes SQLite pour stocker des références à des mouvements détectés ou des températures associées à la date et l'heure.

    J'espère avoir aidé!

  3. #3
    Rédacteur

    Homme Profil pro
    Architecte de système d'information
    Inscrit en
    Novembre 2006
    Messages
    503
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Suisse

    Informations professionnelles :
    Activité : Architecte de système d'information
    Secteur : Transports

    Informations forums :
    Inscription : Novembre 2006
    Messages : 503
    Par défaut
    Citation Envoyé par boijea Voir le message
    La méthode close() d'un objet de Connexion fera l'écriture dans la base de données.
    Où commit(). Cela dépend de ce qu'on veut et cela peux se compliquer sérieusement avec du rollback: https://docs.oracle.com/javase/tutor...nsactions.html

    Je viens seulement maintenant de vraiment regarder ton code et j'ai vu un close().
    Des mouchards ... pourquoi!
    Avec Eclipse par exemple, en Debug mode, tu essaies de stopper sur le close() et avant sur finalize() qui n'est peut-être jamais appelé.

  4. #4
    Membre très actif

    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    486
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 486
    Billets dans le blog
    5
    Par défaut
    Pour commencer, je suis d'accord avec le commentaire précédent: Il faut séparer les logique (interface, sauvegarde en BDD, modèle...)
    Tout ce qui dépend de la base de donnée n'a rien à faire dans la classe Ecran.
    On ne doit juste avoir qu'une classe (Mieux, une interface) PersonneDAO qui permettra de faire la sauvegarde en BDD.

    D'ailleurs, je me pose une question. Je ne voie pas où est instancié l'objet pDAO dans la classe Ecran.

    Mais en général, il ne faut rien qui s'apparente dans la classe Ecran à du JDBC. C'est le rôle de la classe PersonneDAO de sauvegarder la personne.

    Par contre, sur la méthode close(), je ne suis pas d'accord avec le commentaire précédent.
    La méthode close() sert à fermer les flux (Principalement OutputStream et InputStream, ainsi que les connexions à la base de données).

    Après chaque usage, il est indispensable de fermer les flux!

    Depuis Java 7, on a introduit les interfaces Closeable et AutoCloseable.
    On utilise le try-ressource.

    Soit dans le cas d'une BDD:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
     
    try(Connection conn = getConnection(),PreparedStatement ps = conn.prepareStatement(sql)){
    ...
    }
    La suite se fait tout seul, on utilise:
    Tu trouvera des indications sur la FAQ JDBC:
    https://java.developpez.com/faq/jdbc/

    Cordialement.

  5. #5
    Rédacteur

    Homme Profil pro
    Architecte de système d'information
    Inscrit en
    Novembre 2006
    Messages
    503
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Suisse

    Informations professionnelles :
    Activité : Architecte de système d'information
    Secteur : Transports

    Informations forums :
    Inscription : Novembre 2006
    Messages : 503
    Par défaut
    Citation Envoyé par PhilippeGibault Voir le message

    Par contre, sur la méthode close(), je ne suis pas d'accord avec le commentaire précédent.
    La méthode close() sert à fermer les flux (Principalement OutputStream et InputStream, ainsi que les connexions à la base de données).

    Après chaque usage, il est indispensable de fermer les flux!
    J'avais écrit cela hier car c'était clair pour moi dès qu'on découple correctement en classe et méthode.
    J'avais effacé le commentaire, car ma réponse devenait trop grosse pour l'auteur de l'article dont je ne connais pas l'expérience.
    En résumé pour un "insert": une méthode pour ouvrir la connexion, on insère, et on close(). A chaque fois. Et une classe de test pour cette classe et méthode.

Discussions similaires

  1. [WS 2008 R2] Citrix n'arrive pas à se connecter à une autre classe que user de l'AD
    Par Christophe P. dans le forum Windows Serveur
    Réponses: 1
    Dernier message: 08/09/2017, 14h20
  2. Variable accessible par différentes classe
    Par jbidou88 dans le forum Langage
    Réponses: 6
    Dernier message: 03/05/2006, 10h27
  3. Réponses: 2
    Dernier message: 21/04/2006, 14h32
  4. Je n'arrive pas à me connecter au chat
    Par méphistopheles dans le forum Mode d'emploi & aide aux nouveaux
    Réponses: 2
    Dernier message: 27/03/2006, 21h16
  5. Windows sockets : ne peut pas me connecter au serveur...
    Par kernigansnotdead dans le forum Windows
    Réponses: 13
    Dernier message: 11/09/2005, 16h00

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo