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

JDBC Java Discussion :

il n'exécute pas un java.sql.PreparedStatement


Sujet :

JDBC Java

  1. #1
    Membre régulier
    Profil pro
    Étudiant
    Inscrit en
    Avril 2006
    Messages
    110
    Détails du profil
    Informations personnelles :
    Âge : 39
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Avril 2006
    Messages : 110
    Points : 91
    Points
    91
    Par défaut il n'exécute pas un java.sql.PreparedStatement
    bonjour,
    je travaille sur un exercice, dans cet exercice, je dois communiquer avec un serveur ibm as400 et lorsque je tente de modifier un enregistrement de ma table "produits" cad dans une méthode il saute mon code à partir de PreparedStatement et donc la modification n'est pas effective ! le problème vient de la classe ProduitDB.modifier qui est appelé depuis la méthode modifProduit() de la classe main.

    structure de la table client :

    numprod | descr | phtva => prix hors tva d'un article
    => description ex: amd athlon 64 ...
    => numéro de produit [Pxxxx] debut P00001 ...

    voici mon code :


    produit.java

    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
     
    public class Produit{
    /*attributs*/
        protected String numProd;
        protected String descr;
        protected double phtva;
    /*constructeurs*/
        public Produit(){
    	this.numProd=null;
    	this.descr=null;
    	this.phtva=(double)0;
        }
        public Produit(String numProd, 
                    	String descr, 
                            double phtva){
    	this.setNumProd(numProd);
    	this.setDescr(descr);
    	this.setPhtva(phtva);
        }
    /*setters*/
        public void setNumProd(String numProd){
        	this.numProd=numProd;
        }
        public void setDescr(String descr){
        	this.descr=descr;
        }
        public void setPhtva(double phtva){
        	this.phtva=phtva;
        }
    /*getters*/
        public String getNumProd(){
        	return this.numProd;
        }
        public String getDescr(){
        	return this.descr;
        }
        public double getPhtva(){
    	return this.phtva;
        }
    }
    produitDB.java

    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
     
    import java.sql.*;
    import java.util.*;
    public class ProduitDB extends Produit{
        protected static Connection dbConnect=null;
        public static Exception erreur=null;
        public ProduitDB() {
        }
     
        public Connection getDbConnect() {
            return dbConnect;
        }
        public ProduitDB(String numProd,
                            String descr,
                            double phtva){
            super(numProd,descr,phtva);
            this.ajouter();
        }
        public ProduitDB(String descr,
                        double phtva){
            super("P00000",descr,phtva);
            this.ajouter();
            this.setNumProd(this.rechNumProd()); //on recherche un numéro de produit avant validation
        }
     
        public static void setConnection(Connection nouvdbConnect){
            dbConnect=nouvdbConnect;
        }
        protected String rechNumProd(){//méthode qui permet de rechercher un numéro de produit 
            String NumeroProduit=null; //variable utiliser pour récupérer le numéro de produit si il existe
            try{
                String qry="select numprod from produits where descr=?"; 
                //represente une requete select, les "?" représente 1 paramètre que l'on identifiera grâce à un numéro'
                PreparedStatement pstm=dbConnect.prepareStatement(qry); 
                //j'encapsule mon select dans mon instance de Connection (java.sql.Connection) et ma connection sera encapsuler dans mon objet PreparedStatement
                //PreparedStatement ??? <<A SQL statement is precompiled and stored in a PreparedStatement object>>
                pstm.setString(1,this.numProd); 
                //je passe un numéro de produit comme paramètre et il remplacera le premier (et ici seul) point d'interrogation
                ResultSet rs=pstm.executeQuery();
                //ici on execute la requête précompilé et on stocke le résultat ds un résultset
                if(rs.next()){//si il y a un résultat dispo (cad minimul 1 ligne), on s'attend dans notre cas à avoir qu'une ligne en guise de résultat'
                    NumeroProduit=rs.getString(1); 
                }
                else{
                    NumeroProduit="NUMERO INTROUVABLE";
                }
                pstm.close();
                return NumeroProduit;
            }
            catch(Exception e){
                erreur=e;
                return "ERREUR";
            }
        }
        public void ajouter(){
            try{
                String qry="insert into produits(numprod,descr,phtva) values(?,?,?)";
                PreparedStatement pstm=dbConnect.prepareStatement(qry);
                pstm.setString(1,this.numProd);
                pstm.setString(2,this.descr);
                pstm.setDouble(3,this.phtva);
                pstm.executeUpdate(); //on n'a pas a stocker de résultat donc pas de resultset
                pstm.close();
            }
            catch(Exception e){
                erreur=e;
            }
        }
        public static ProduitDB rechNumProd(String numeroDeProduit){//rechercher un numéro de produit
            String numProduit=null;
            String description=null;
            double prxhtva=(double)0;
            erreur=null;
            try{
                String qry="select * from produits where numprod=?";
                PreparedStatement pstm=dbConnect.prepareStatement(qry);
                pstm.setString(1,numeroDeProduit);
                ResultSet rs=pstm.executeQuery();
                if(rs.next()){
                    System.out.println("TEST : je suis dans rs.next() dans rechNumProd");
                    numProduit=rs.getString("numprod");
                    description=rs.getString("descr");
                    prxhtva=rs.getDouble("phtva");
                    pstm.close();
                    ProduitDB p=new ProduitDB(numProduit,description,prxhtva);
                    return p;
                }
                else{
                    System.out.println("TEST : rs.next contient rien");
                    pstm.close();
                    throw new Exception("Code inconnu");
                }
            }
            catch(Exception e){
                erreur=e;
                return null;
            }
        }
        public void modifier(){//méthode où le problème se situe
            try{
                int nLigne = 0;
                String qry="UPDATE produits set descr=?, phtva=? where numcli=?";
                System.out.println("avant preparedStat...");
                PreparedStatement pstm=dbConnect.prepareStatement(qry); //a partir d'ici le code est comme renié d'où le fait qu'il ne modifie pas ... et sans me provoquer d'erreur !
                pstm.setString(1,this.getNumProd());
                pstm.setString(2,this.getDescr());
                pstm.setDouble(3,this.getPhtva());
                try{
     
                nLigne=pstm.executeUpdate();
                }
                catch(Exception e){
                    System.out.println("erreur executeUpdate");
                }
                if(nLigne==0) throw new Exception("aucune ligne mise à jour");
                pstm.close();
            }
            catch(Exception e){
                erreur=e;
            }
        }
        public void supprimer(){
            int nLigne=0;
            try{
                String qry="delete from produits where numprod=?";
                PreparedStatement pstm=dbConnect.prepareStatement(qry);
                pstm.setString(1,numProd);
                nLigne=pstm.executeUpdate();
                pstm.close();
                if(nLigne==0) throw new Exception("aucune ligne effacée");           
            }
            catch(Exception e){
                erreur=e;
            }
        }
        //arrivé ici
     
        public static Vector rechNom/*rechMotsClef ou rechDescr*/(String descRech){//a la fin du projet changer nom ="rechMotsClefDescr"
            Vector plusieurs=new Vector();
            String qry="select * from produits where descr like ?"; //si ca foire on revient a la version précédente !!!!
            try{
                PreparedStatement pstm=dbConnect.prepareStatement(qry);
                pstm.setString(1,descRech);
                ResultSet rs=pstm.executeQuery();
                while(rs.next()){
                        String numProduit=rs.getString("numprod");
                        String description=rs.getString("descr");
                        double prixhtva=rs.getDouble("phtva");
                        plusieurs.add(new ProduitDB(numProduit,description,prixhtva));
                }
                pstm.close();
            }
            catch(Exception e){
                erreur=e;
            }
            return plusieurs;
        }
    }
    main.java

    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
     
    import java.sql.*;
    import java.util.*;
    /* @author Manu */
    public class Main {
        public Main(){
            DB2Connection db2c=new DB2Connection();
            Connection dbc=db2c.getConnection();
            ProduitDB.setConnection(dbc);
            menu();
        }
        public void menu(){
            int ch=0;
            do{
                do{
                   System.out.println("<1> NOUVEAU PRODUIT");
                   System.out.println("<2> TROUVER UN PRODUIT GRACE AU NUMERO DE PRODUIT");
                   System.out.println("<3> TROUVER UN PRODUIT GRACE A SON DESCRIPTIF");
                   System.out.println("<4> MODIFIER UN PRODUIT");
                   System.out.println("<5> SUPPRIMER UN PRODUIT");
                   //System.out.println("<6> SORTIR LA LISTE DES PRODUITS");
                   System.out.println("<6> QUITTER");
                   System.out.println("CHOIX > ");
                   ch=Reader.readerInt();
                }
                while(ch<1 && ch>6);
                switch(ch){
                    case 1 : //on souhaite ajouter un produit
                        this.nouvProd();
                        break;
                    case 2 : //on souhaite rechercher un produit grace à son numéro de produit
                        this.rechNumProd();
                        break;
                    case 3 : //on souhaite rechercher un produit grace a son descriptif
                        this.rechDescr();
                        break;
                    case 4 : //on souhaite modifier un produit
                        this.modifProduit();
                        break;
                    case 5 : //on souhaite supprimer un produit
                        this.supprProduit();
                        break;
                    case 6 : 
                        //lancer JServerAs400.java
                        break;
                    default:
                        System.out.println("erreur");
                        break;
                }
            }
            while(ch!=6);
        }
        protected void supprProduit(){
            ProduitDB produit=recherche();
            if(produit!=null){
                produit.supprimer();
            }
        }
        protected void modifProduit(){
            ProduitDB produit=recherche();
            if(produit!=null){
                System.out.println("nouvelle description :");
                String descr=Reader.readerString();
                produit.setDescr(descr);
                System.out.println("voulez-vous modifier le prix (1/0) ? ");
                int choix=Reader.readerInt();
                if(choix==1){
                    double prix=Reader.readerDouble();
                    produit.setPhtva(prix);
                }
                produit.modifier();
            }
        }
        protected ProduitDB recherche(){
            int choix;
            do{
                System.out.println("1 - Recherche par numéro de produit");
                System.out.println("2 - Recherche par descriptif");
                System.out.println("CHOIX > ");
                choix=Reader.readerInt();
                switch(choix){
                    case 1 : 
                        return this.rechNumProd();
                    case 2 :
                        return this.rechDescr();
                    default : System.out.println("-- CHOIX ERRONE --");
     
                }
            }
            while(true);
        }
        protected ProduitDB rechDescr(){
            ProduitDB produit=null;
            System.out.println("entrez un mots clef pour rechercher un produit : ");
            String motClef=Reader.readerString();
            Vector DescrRech=ProduitDB.rechNom("%"+motClef+"%");
            if(DescrRech.size()==0){
                System.out.println("-- AUCUN PRODUIT CORRESPONDANT --");
                return null;
            }
            System.out.println("0 - RETOUR");
            for(int i=0;i<DescrRech.size();i++){
                produit=(ProduitDB)DescrRech.elementAt(i);
                System.out.println((i+1)+" - ");
                affiche(produit);
            }
            boolean erreurChoix;
            do{
                erreurChoix=false;
                System.out.println("INDIQUER LE NUMERO A EXTRAIRE [0,"+DescrRech.size()+"] : ");
                int n=Reader.readerInt();
                if(n==0){
                    return null;
                }
                else{
                    if((n>0)&&(n<=DescrRech.size())){
                        produit=(ProduitDB)DescrRech.elementAt(n-1);
                    }
                    else{
                        System.out.println("-- POSITION ERRONE --");
                        erreurChoix=true;
                    }
                }
            }
            while(erreurChoix);
            return produit;
        }
        public ProduitDB rechNumProd(){
            ProduitDB produit=null;
            System.out.println("ATTENTION TOUS LES NUMEROS DE PRODUIT SONT STRUCTURE [Pxxxxx] ");
            System.out.println("ENTREZ LE NUMERO DE PRODUIT CORRECTE A RECHERCHER :");
            String numProdRech=Reader.readerString();
            produit=ProduitDB.rechNumProd(numProdRech);
            if(produit!=null){
                affiche(produit);
                return produit;
            }
            else{
                System.out.println("-- NUMERO DE PRODUIT INCONNU --");
                return null;
            }
        }
        public void affiche(ProduitDB produit){
            System.out.println("numéro de produit : "+produit.getNumProd());
            System.out.println("description produit : "+produit.getDescr());
            System.out.println("prix hors tva : "+produit.getPhtva()+" €");
            System.out.println("prix tva comprise : "+(produit.getPhtva()*1.21)+" €");
     
        }
        public void nouvProd(){
            System.out.println("NUMERO DE PRODUIT :");
            String numProd=Reader.readerString();
            System.out.println("DESCRIPTION DU PRODUIT :");
            String descr=Reader.readerString();
            System.out.println("PRIX HORS TVA :");
            double phtva=Reader.readerDouble();
     
            ProduitDB produit=new ProduitDB(numProd,descr,phtva);
            System.out.println("LE NUMERO DU PRODUIT EST : "+produit.getNumProd());
            if(ProduitDB.erreur!=null){
                System.out.println("erreur lors de la création :"+produit.erreur);
            }
        }
        public static void main(String[] args) {
            Main prg=new Main();
        }
     
    }
    DB2Connection.java (qui me sert à me connecter au serveur as400

    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
     
    import java.sql.*;
    import com.ibm.as400.access.*;
    import java.util.*;
     
    public class DB2Connection 
    {
    	public  static final String LOCALSERVER = "as400i.lan";
      	public  static final String REMOTESERVER = "as400.hepmbc.be";
      	protected String serverName = LOCALSERVER;
      	protected String username;
      	protected String password;
      	protected String library;
        protected static Vector poolConnect=new Vector();
     
      	public DB2Connection() 
      	{
        	FenetreConnexion fc = new FenetreConnexion();
        	while(!fc.logOK()) ;
        	username=fc.getLogin();
        	library=username;
        	password=fc.getPassword();
        	if(!fc.isLan()) 
        		serverName=REMOTESERVER;
        	fc.dispose();
        }   
     
      	public DB2Connection(String library) 
      	{
        	this();
        	this.library = library;
        }   
     
      	public DB2Connection(String username,String password,String library)
      	{
          	this.username=username;
          	this.password=password;
          	this.library=library;
      	}   
     
      	public DB2Connection(String username,String password,String library ,String serverName) 
      	{
       		this(username,password,library);
       		this.serverName=serverName;
     	}    
     
     	public Connection getConnection() 
     	{
      		try 
      		{
         		java.sql.DriverManager.registerDriver(new com.ibm.as400.access.AS400JDBCDriver()); 
         		String url = "jdbc:as400://"+serverName+"/"+library;
         		Connection dbc = DriverManager.getConnection(url, username,password);
         		poolConnect.addElement(dbc);
         		return dbc;
         	}
        	catch(Exception e) 
        	{
         		System.out.println("erreur de connexion "+e);
         		e.printStackTrace();
         		return null ;
        	}       
      	}
     
     	public void closeConnection(Connection dbc)
     	{
      		try 
      		{
          		dbc.close();
          		poolConnect.remove(dbc);
      		}	   
      		catch(Exception e)
      		{
       			System.out.println("erreur de fermeture "+e);
       			e.printStackTrace();
       		}    
      	}
     
     	public void closeAllConnections()
     	{
         	while(poolConnect.size()>0)
         	{
             	Connection dbc=(Connection)poolConnect.elementAt(0);
             	closeConnection(dbc);
            }
        }
    }
    FenetreConnection.java : l'interface de DB2Connection

    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
     
    import java.awt.*;
    import java.awt.event.*;
     
    public class FenetreConnexion extends Frame implements ActionListener 
    {
    	private TextField log,pass;
       	private Label l1,l2;
       	private Checkbox c1,c2;
       	private CheckboxGroup cb;
       	private String login,password;
       	private boolean ok=false;
       	private boolean lan=true;
     
       	public FenetreConnexion() 
       	{
         	setSize(300,150);
         	GridLayout lay = new GridLayout(3,2,5,5);
            setBackground(Color.blue);
         	setTitle("DB2 Connexion ");
         	setLayout(lay);
         	l1 = new Label("LOGIN");
         	log = new TextField();  
         	l2= new Label("PASSWORD");
         	pass= new TextField();
         	pass.setEchoChar('*');
         	c1 = new Checkbox("LAN");
         	c2 = new Checkbox("WAN");
         	cb = new CheckboxGroup();
         	c1.setCheckboxGroup(cb);
         	c2.setCheckboxGroup(cb);
         	cb.setSelectedCheckbox(c1);
         	pass.addActionListener(this);
         	addWindowListener(new WindowAdapter()
         	{
         		public void windowClosing(WindowEvent e)
         		{
         	 		System.exit(0);
          		}
          	});    
         	add(l1);
         	add(log);
         	add(l2);
         	add(pass);
         	add(c1);
         	add(c2);
         	setBounds(100,100,250,100);
         	setResizable(false);
            show();
     
        }
     
    	public void actionPerformed(ActionEvent e)
    	{
       		setInfo();
        }
     
        public void setInfo()
        {
       		login = log.getText();
        	password= pass.getText();
        	lan=c1.getState();
        	ok=true;
       	}
     
        public boolean logOK()
        {
          	return ok;
       	}
       	public String getLogin()
       	{
          	return login;
      	}
     
      	public String getPassword()
      	{
           	return password;
      	}         
     
      	public boolean isLan()
      	{
      		return lan;
      	}
     
    }
    Merci d'avoir lu jusqu'ici et encore merci d'avance ...

  2. #2
    in
    in est déconnecté
    Membre expérimenté Avatar de in
    Profil pro
    Inscrit en
    Avril 2003
    Messages
    1 612
    Détails du profil
    Informations personnelles :
    Localisation : France, Finistère (Bretagne)

    Informations forums :
    Inscription : Avril 2003
    Messages : 1 612
    Points : 1 718
    Points
    1 718
    Par défaut
    Je n'ai pas regardé tout le code, merci de ne mettre que l'essentiel ...

    Il faut faire un commit() pour que les modifications soient prises en compte. Je ne crois pas en avoir vu.

    De plus, tu fais des close() de tes statements, c'est bien, mais il faut le faire dans des bloc finally, c'est beaucoup mieux ...
    "If email had been around before the telephone was invented, people would have said, 'Hey, forget email! With this new telephone invention I can actually talk to people!"

    Besoin d'une nouvelle méthode pour développer ? -> http://www.la-rache.com/

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 2
    Dernier message: 13/12/2012, 11h17
  2. [SQL] Requête UPDATE qui ne s'exécute pas avec PHP
    Par xplose dans le forum PHP & Base de données
    Réponses: 6
    Dernier message: 16/08/2007, 09h42
  3. ms sql server 2000 : ".exe" qui ne s'exécute pas
    Par nyko_kliko dans le forum MS SQL Server
    Réponses: 3
    Dernier message: 08/08/2006, 16h15
  4. [MySQL] requete sql qui ne s'exécute pas
    Par anto48_4 dans le forum PHP & Base de données
    Réponses: 15
    Dernier message: 16/03/2006, 09h12

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