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

Java Discussion :

interface authentification java et connexion à une base de données mysql


Sujet :

Java

  1. #1
    Membre du Club
    Inscrit en
    Novembre 2009
    Messages
    89
    Détails du profil
    Informations forums :
    Inscription : Novembre 2009
    Messages : 89
    Points : 40
    Points
    40
    Par défaut interface authentification java et connexion à une base de données mysql
    bonsoir, je suis débutant en java et j'aimerais créer une interface d'authentification avec java et ce en testant si login et mot de passe introduits de trouvent dans la table gestionnaire ou pas!
    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
     
    import com.mysql.jdbc.Connection;
    import com.mysql.jdbc.Statement;
    import java.sql.DriverManager;
    import java.sql.ResultSet;
    import java.sql.SQLException;
     
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
     
    /*
     * authentification.java
     *
     * Created on 28 janv. 2010, 14:18:16
     */
    import java.sql.*;
     
    /**
     *
     * @author 2MBA
     */
    public class authentification extends javax.swing.JFrame {
     
        /** Creates new form authentification */
        public authentification() {
            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.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
     
            jLabel1 = new javax.swing.JLabel();
            jLabel2 = new javax.swing.JLabel();
            jLabel3 = new javax.swing.JLabel();
            textlogin = new javax.swing.JTextField();
            textmdp = new javax.swing.JTextField();
            btnseconnecter = new javax.swing.JButton();
     
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
     
            jLabel1.setText("authentification");
     
            jLabel2.setText("login");
     
            jLabel3.setText("mot de passe");
     
            textlogin.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    textloginActionPerformed(evt);
                }
            });
     
            textmdp.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    textmdpActionPerformed(evt);
                }
            });
     
            btnseconnecter.setText("se connecter");
            btnseconnecter.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    btnseconnecterActionPerformed(evt);
                }
            });
     
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addGap(52, 52, 52)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jLabel3)
                                .addComponent(jLabel2))
                            .addGap(74, 74, 74)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(textmdp, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(textlogin, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGroup(layout.createSequentialGroup()
                            .addGap(154, 154, 154)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(btnseconnecter)
                                .addComponent(jLabel1))))
                    .addContainerGap(117, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(22, 22, 22)
                    .addComponent(jLabel1)
                    .addGap(37, 37, 37)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(textlogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(60, 60, 60)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel3)
                        .addComponent(textmdp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(52, 52, 52)
                    .addComponent(btnseconnecter)
                    .addContainerGap(52, Short.MAX_VALUE))
            );
     
            pack();
        }// </editor-fold>                        
     
        private void textloginActionPerformed(java.awt.event.ActionEvent evt) {                                          
        }                                         
     
        private void textmdpActionPerformed(java.awt.event.ActionEvent evt) {                                        
            // TODO add your handling code here:
        }                                       
     
        private void btnseconnecterActionPerformed(java.awt.event.ActionEvent evt) {                                               
     
     //Param de connection a la base de donné
            String url = "jdbc:mysql://localhost:3306/parking"; // ex : postgresql://localhost/postgres
            String log = "root";
            String pass= "";
            String login = "textlogin.getText()";
            String motdepasse = "textmdp.getText()";
     
            try
            {
                // connection
                Connection connection = (Connection) DriverManager.getConnection(url,log,pass);
                //interaction avec la base
                Statement st = (Statement) connection.createStatement();
     
                //Traitement
     
    String sql = "SELECT * FROM gestionnaire g WHERE ((g.login == login ) AND (g.mdp == motdepasse)) ";
    ResultSet resultat = st.executeQuery(sql);
    if (resultat == null)
    { System.out.println ("erreur");}
    else
        { System.out.println ("correct");}
    //traitement
                st.close();
                connection.close();
            }
            catch(SQLException sqle)
            {
               sqle.printStackTrace();
            }
        }                                              
     
        /**
        * @param args the command line arguments
        */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new authentification().setVisible(true);
                }
            });
        }
     
        // Variables declaration - do not modify                     
        private javax.swing.JButton btnseconnecter;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JTextField textlogin;
        private javax.swing.JTextField textmdp;
        // End of variables declaration                   
    }
    lorsque j'exécute , mon code est plein 'erreurs
    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
     
    com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Erreur de syntaxe près de '== login ) AND (g.mdp == motdepasse))' à la ligne 1
            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:39)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:27)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:513)
            at com.mysql.jdbc.Util.handleNewInstance(Util.java:406)
            at com.mysql.jdbc.Util.getInstance(Util.java:381)
            at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1030)
            at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956)
            at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491)
            at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423)
            at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936)
            at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060)
            at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2536)
            at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2465)
            at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1383)
            at authentification.btnseconnecterActionPerformed(authentification.java:146)
            at authentification.access$200(authentification.java:24)
            at authentification$3.actionPerformed(authentification.java:70)
            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:6038)
            at javax.swing.JComponent.processMouseEvent(JComponent.java:3260)
            at java.awt.Component.processEvent(Component.java:5803)
            at java.awt.Container.processEvent(Container.java:2058)
            at java.awt.Component.dispatchEventImpl(Component.java:4410)
            at java.awt.Container.dispatchEventImpl(Container.java:2116)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            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:2429)
            at java.awt.Component.dispatchEvent(Component.java:4240)
            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)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
            at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
            at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
    BUILD SUCCESSFUL (total time: 2 minutes 22 seconds)
    je devrais je ?
    merci d'avance

  2. #2
    Expert confirmé
    Profil pro
    Inscrit en
    Août 2006
    Messages
    3 274
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Août 2006
    Messages : 3 274
    Points : 4 141
    Points
    4 141
    Par défaut
    C'est = en SQL et non pas ==.
    De plus login sera écrit en dur dans ta requête, ton login saisi ne sera pas pris en compte. Utilise plutôt la classe PrepareStatement et les methodes setXXX pour "setter" les paramètres de ta requête.

  3. #3
    Membre du Club
    Inscrit en
    Novembre 2009
    Messages
    89
    Détails du profil
    Informations forums :
    Inscription : Novembre 2009
    Messages : 89
    Points : 40
    Points
    40
    Par défaut
    merci beaucoup pour votre réponse, voila, j'ai changé mon code mais malheureusement ça marcha pas , il affiche "correcte" même si le login saisi est faux!
    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
     
        private void btnseconnecterActionPerformed(java.awt.event.ActionEvent evt) {                                               
     
     
          PreparedStatement teste = null;
          String login = "textlogin.getText()";
          ResultSet rs = null;
          String url = "jdbc:mysql://localhost:3306/parking";
          String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
          String user = "root";
          String password = "";
     
            try {
     
          Class.forName(driver);
          Connection connection = (Connection) DriverManager.getConnection(url,user, password);
          String sql = "SELECT * FROM gestionnaire WHERE login = ?";
          teste = connection.prepareStatement(sql);
          teste.setString(1, login ); 
          rs = teste.executeQuery();
         if (rs == null)
    { System.out.println ("erreur");}
    else
        { System.out.println ("correct");}
     
          connection.close();
        }
            catch (ClassNotFoundException cnfe) {
          System.err.println(cnfe);
        }
          catch (SQLException sqle) {
          System.err.println(sqle);
        }
        }
     
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable(){
                public void run()
                {
                    new authentification().setVisible(true);
                }});
        }                     
        private javax.swing.JButton btnseconnecter;
        private javax.swing.JLabel jLabel1;
        private javax.swing.JLabel jLabel2;
        private javax.swing.JLabel jLabel3;
        private javax.swing.JTextField textlogin;
        private javax.swing.JTextField textmdp;
        // End of variables declaration                   
    }

  4. #4
    Membre régulier
    Profil pro
    Inscrit en
    Mars 2009
    Messages
    111
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Mars 2009
    Messages : 111
    Points : 118
    Points
    118
    Par défaut
    Citation Envoyé par élève_ingénieur Voir le message
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
          String login = "textlogin.getText()";
    En faut là tu ne récupère pas le texte contenu dans textlogin, mais tu met dans la variable login la chaine de caractères "textlogin.getText()".
    Du coup quand tu met la valeur de login dans ton preparedStatement, c'est cette valeur ta requete ressemble à
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    SELECT * FROM gestionnaire WHERE login = textlogin.getText()
    Et là ton SQL n'est pas valide.
    Il faudrait faire
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
     
    String login = textlogin.getText();
    Un geek, c'est quelqu'un qui croit qu'il y a 1024m dans 1km...

    Il y a 10 types de geeks, ceux qui savent compter en binaire et les autres...

  5. #5
    Membre du Club
    Inscrit en
    Novembre 2009
    Messages
    89
    Détails du profil
    Informations forums :
    Inscription : Novembre 2009
    Messages : 89
    Points : 40
    Points
    40
    Par défaut
    merci infiniment, ça fonctionne

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

Discussions similaires

  1. Réponses: 0
    Dernier message: 04/10/2012, 15h42
  2. Réponses: 1
    Dernier message: 19/07/2007, 21h09
  3. Problème de connexion à une base de donnée MySQL
    Par casho dans le forum VB 6 et antérieur
    Réponses: 2
    Dernier message: 27/06/2007, 14h04
  4. connexion à une base de données mysql depuis c++
    Par btissama4 dans le forum C++
    Réponses: 4
    Dernier message: 16/02/2007, 11h55
  5. Connexion à une base de données mysql via access
    Par eautret dans le forum Access
    Réponses: 2
    Dernier message: 07/04/2006, 10h02

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