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 :

Effecute une requête MySQL


Sujet :

JDBC Java

  1. #1
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Février 2008
    Messages
    140
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2008
    Messages : 140
    Points : 31
    Points
    31
    Par défaut Effecute une requête MySQL
    Bonjour, j'ai crée une base de données nommée "snecma" . Il y a une table "utilisateur" qui comprend les champs suivants: ID_UTIL (contient des numéros 1, 2, 3, 4...); LOGIN...

    Je veux faire une requete sur ID_UTIL. J'ai donc tapé ceci:
    rs = stmt.executeQuery("SELECT * From utilisateur");

    Mais ensuite je voudrais récupérer ce qu'il y a dans ID_UTIL dans une variable.

    Et savoir si dans ID_UTIL il y a le numéro 3 par exemple.
    Mais je n'y arrive pas, pouvez-vous m'aider s'il vous plait ?

    Merci d'avance.

  2. #2
    Membre habitué
    Inscrit en
    Octobre 2005
    Messages
    259
    Détails du profil
    Informations personnelles :
    Âge : 41

    Informations forums :
    Inscription : Octobre 2005
    Messages : 259
    Points : 126
    Points
    126
    Par défaut
    Salut,

    Tu pourrais déjà faire
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    SELECT ID_UTIL FROM UTILISATEURS
    Ensuite tu fais simplement
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    int id = rs.getInt(1);
    if (id == 3) {
    // faire le traitement
    }

  3. #3
    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
    Citation Envoyé par mimi51340 Voir le message
    Mais je n'y arrive pas, pouvez-vous m'aider s'il vous plait ?
    Pour qu'on t'aide il faudrait nous dire où tu bloques. Montre nous ce que tu as fait, ce que tu ne comprends pas, les exceptions ...

    Autre remarque : tu devrais (au minimum) aller voir dans la FAQ quand tu ne sais pas comment faire un truc. Il n'y aura pas toujours un gentil gids01 pour t'aider sur des trucs si simples ...
    "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/

  4. #4
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Février 2008
    Messages
    140
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2008
    Messages : 140
    Points : 31
    Points
    31
    Par défaut
    En faite pour l'instant il s'agit d'un essai de connexion à mon serveur MySQL. J'ai donc mis des numéros "au pif" dans la colonne ID_UTIL (1, 2, 3, 4...) mais en réalité ça sera un nombre à 13 chiffres. C'est pour ça qu'en attendant, j'ai déclarer un String NumBadge = "3".

    Voici mon code:

    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
     
    /*
     * Connection.java
     *
     * Created on 11 mars 2008, 15:45
     */
     
    package Test;
     
    import java.sql.*;
    import java.lang.*;
     
    /**
     *
     * @author  adminlocal
     */
    public class Autorisation extends javax.swing.JFrame {
     
         String NumCodeBarre; 
         String NumBadge = "3";
        /** Creates new form Connection */
        public Autorisation() {
            initComponents();
        }
     
        /** 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.
         */
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
     
            jTextFieldAutorisation = new javax.swing.JTextField();
            jButtonBadge = new javax.swing.JButton();
            jTextFieldNumBadge = new javax.swing.JTextField();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
            jTextFieldAutorisation.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextFieldAutorisationActionPerformed(evt);
                }
            });
     
            jButtonBadge.setText("Passage du badge");
            jButtonBadge.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButtonBadgeActionPerformed(evt);
                }
            });
     
            jTextFieldNumBadge.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jTextFieldNumBadgeActionPerformed(evt);
                }
            });
     
            org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .addContainerGap(108, Short.MAX_VALUE)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                            .add(jTextFieldAutorisation, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 186, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                            .add(106, 106, 106))
                        .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                            .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                                .add(org.jdesktop.layout.GroupLayout.LEADING, jTextFieldNumBadge)
                                .add(org.jdesktop.layout.GroupLayout.LEADING, jButtonBadge, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .add(136, 136, 136))))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(layout.createSequentialGroup()
                    .add(68, 68, 68)
                    .add(jTextFieldNumBadge, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(60, 60, 60)
                    .add(jButtonBadge)
                    .add(48, 48, 48)
                    .add(jTextFieldAutorisation, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(62, Short.MAX_VALUE))
            );
     
            pack();
        }// </editor-fold>                        
     
        private void jTextFieldAutorisationActionPerformed(java.awt.event.ActionEvent evt) {                                                       
            // TODO add your handling code here:
    }                                                      
     
        private void jButtonBadgeActionPerformed(java.awt.event.ActionEvent evt) {                                             
            // TODO add your handling code here:
            Connection();
     
        }                                            
     
     
     
        /**
         * @param args the command line arguments
         */
     
        public void Connection(){
            Connection conn;
            Statement stmt;
            ResultSet rs;
            String pilote = "org.gjt.mm.mysql.Driver";
            String url = new String("jdbc:mysql://10.104.100.57:3306/snecma");
     
            try
    	  {
    			Class.forName(pilote);			 
     
    			conn = DriverManager.getConnection(url,"root","root");
     
    			stmt = conn.createStatement();
     
                            rs = stmt.executeQuery("SELECT * From utilisateur");
     
     
     
     
    			while (rs.next())
    			{
     
                                System.out.println(rs.getString(1)+ " " + rs.getString(2) + " " + rs.getString(3)+ " " + rs.getString(4) + "\n ");
     
     
    			}		
     
                            if(NumBadge.equals(NumCodeBarre))
                                     AccesAutorise();
                            else
                                     AccesRefuse();
     
    			rs.close();
    			stmt.close();
    			conn.close();
     
    	  }
     
    	  catch ( SQLException E)
    	  {
                     System.out.println("SQLException: " + E.getMessage());
                     System.out.println("SQLState:     " + E.getSQLState());
                     System.out.println("VendorError:  " + E.getErrorCode());
    	  }
    	  catch ( ClassNotFoundException E)
    	  {
    	  	E.printStackTrace();
    	  }
        }
     
     
        public void AccesAutorise() {
            jTextFieldAutorisation.setText("L'accès est autorisé");
        }
     
        public void AccesRefuse() {
            jTextFieldAutorisation.setText("L'accès est refusé");
        }
     
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new Autorisation().setVisible(true);
                }
            });
     
        }
     
        // Variables declaration - do not modify                     
        private javax.swing.JButton jButtonBadge;
        private javax.swing.JTextField jTextFieldAutorisation;
        private javax.swing.JTextField jTextFieldNumBadge;
        // End of variables declaration                   
     
    }
    Je veux tester si NumBadge est égal à un numéro contenu dans ID_UTIL. Et le n° de ID_UTIL je voudrai qu'il soit envoyé dans la variable NumCodeBarre mais je ne sais pas comment faire.

    Merci pour votre aide.

  5. #5
    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
    Heu ... quand tu fais

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    while (rs.next()) {
            System.out.println(rs.getString(1)+ " " + rs.getString(2) + " " + rs.getString(3)+ " " + rs.getString(4) + "\n ");
    }
    Un des getString affiche la valeur que tu cherches non ?
    Dans ce cas au lieu d'afficher la valeur et bien tu la met dans la variable NumBadge ...

    Je vois vraiment pas où tu bloques ...
    "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/

  6. #6
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Février 2008
    Messages
    140
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2008
    Messages : 140
    Points : 31
    Points
    31
    Par défaut
    j'ai cette erreur maintenant:
    SQLException: Illegal operation on empty result set.
    SQLState: S1000
    VendorError: 0


    Ceci provient de quoi ?
    Merci encore.

  7. #7
    Membre chevronné Avatar de guigui5931
    Profil pro
    Chef de projet NTIC
    Inscrit en
    Avril 2006
    Messages
    1 667
    Détails du profil
    Informations personnelles :
    Âge : 37
    Localisation : France, Nord (Nord Pas de Calais)

    Informations professionnelles :
    Activité : Chef de projet NTIC
    Secteur : High Tech - Multimédia et Internet

    Informations forums :
    Inscription : Avril 2006
    Messages : 1 667
    Points : 2 232
    Points
    2 232
    Par défaut
    sur quelle ligne cette erreur est-elle indiquée?
    autant l'hiver éclate que l'hétéroclite
    le vrai geek c'est celui qui croit qu'il y a 1024 mètres dans un kilomètre

  8. #8
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Février 2008
    Messages
    140
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2008
    Messages : 140
    Points : 31
    Points
    31
    Par défaut
    cette erreur est résolue mais maintenant j'en ai une autre qui apparaît:

    SQLException: null
    SQLState: S1000
    VendorError: 0

    Ceci provient de quoi ? je ne sais pas.

    merci encore.

  9. #9
    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
    Pour connaitre la ligne qui lève cette exception tu peux utiliser la méthode printStackTrace de l'exception ...

    C'est ça que te demande guigui5931 ...
    "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/

  10. #10
    Nouveau membre du Club
    Profil pro
    Inscrit en
    Février 2008
    Messages
    140
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Février 2008
    Messages : 140
    Points : 31
    Points
    31
    Par défaut
    avec le PrintStackTrace ça me donne ça (je pense que c'est ça que vous me demandez ?):

    Mais je ne sais pas ce que ça peut être comme erreur.

    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
     
     
    SQLException: null
    java.sql.SQLException
            at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1056)
            at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
            at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
            at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:817)
            at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5514)
            at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5434)
            at Test.Autorisation.Connection(Autorisation.java:133)
            at Test.Autorisation.jButtonBadgeActionPerformed(Autorisation.java:94)
            at Test.Autorisation.access$100(Autorisation.java:16)
            at Test.Autorisation$2.actionPerformed(Autorisation.java:47)
            at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
            at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
            at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
            at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
            at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
            at java.awt.Component.processMouseEvent(Component.java:6041)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3265)
            at java.awt.Component.processEvent(Component.java:5806)
            at java.awt.Container.processEvent(Container.java:2058)
            at java.awt.Component.dispatchEventImpl(Component.java:4413)
            at java.awt.Container.dispatchEventImpl(Container.java:2116)
            at java.awt.Component.dispatchEvent(Component.java:4243)
            at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4322)
            at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3986)
            at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3916)
            at java.awt.Container.dispatchEventImpl(Container.java:2102)
            at java.awt.Window.dispatchEventImpl(Window.java:2440)
            at java.awt.Component.dispatchEvent(Component.java:4243)
            at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
            at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
            at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
            at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
    SQLState:     S1000
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
    VendorError:  0
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)

  11. #11
    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
    Oui ...

    et cette ligne

    Citation Envoyé par exception
    at Test.Autorisation.Connection(Autorisation.java:133)
    c'est quoi ?

    (la ligne 133 de ta classe Autorisation )
    "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/

Discussions similaires

  1. Comment faire une requête Mysql
    Par Xavier dans le forum C++Builder
    Réponses: 5
    Dernier message: 01/02/2007, 17h07
  2. besoin d'aide sur une requête mysql
    Par unmulot dans le forum Langage SQL
    Réponses: 5
    Dernier message: 07/07/2006, 13h17
  3. Probleme avec une requête MySQL
    Par Alexlesilex dans le forum Requêtes
    Réponses: 8
    Dernier message: 04/05/2006, 17h48
  4. Intégrer un tableau dans une requête mysql
    Par GarGamel55 dans le forum Requêtes
    Réponses: 5
    Dernier message: 21/02/2006, 19h16
  5. Arrêt de l'exécution d'une requête MySQL dans DELPHI.
    Par joelmarc dans le forum Bases de données
    Réponses: 9
    Dernier message: 11/10/2004, 16h11

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