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 :

Eclipse et base de données


Sujet :

JDBC Java

  1. #1
    Membre à l'essai
    Profil pro
    Réseau informatique
    Inscrit en
    Février 2012
    Messages
    27
    Détails du profil
    Informations personnelles :
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Réseau informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2012
    Messages : 27
    Points : 16
    Points
    16
    Par défaut Eclipse et base de données
    Bonjour,

    Je cherche à faire la sauvegarde d'un formulaire dans une base de données MySQL mais lorsque je remplis le formulaire texte et que je valide, les données ne sont pas enregistrées en base.

    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
    182
    183
    184
    package com.m1.m2;
     
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import java.sql.Connection;
    import java.sql.DriverManager;
     
    import java.sql.Statement;
     
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.UIManager;
     
    import org.dyno.visual.swing.layouts.Constraints;
    import org.dyno.visual.swing.layouts.GroupLayout;
    import org.dyno.visual.swing.layouts.Leading;
     
     
    //VS4E -- DO NOT REMOVE THIS LINE!
    public class _w1 extends JFrame {
     
        private static final long serialVersionUID = 1L;
        private JTextField jTextField0;
        private JButton jButton0;
        private JLabel jLabel0;
        private JTextField jTextField1;
        private JTextField jTextField2;
        private JTextField jTextField3;
        private JLabel jLabel2;
        private JLabel jLabel3;
        private JLabel jLabel1;
     
    private static final String PREFERRED_LOOK_AND_FEEL = "javax.swing.plaf.metal.MetalLookAndFeel";
        public _w1() {
            initComponents();
        }
        private void initComponents() {
            setLayout(new GroupLayout());
            add(getJButton0(), new Constraints(new Leading(172, 62, 10, 10), new Leading(129, 25, 10, 10)));
            add(getJTextField2(), new Constraints(new Leading(62, 206, 12, 12), new Leading(61, 12, 12)));
            add(getJTextField3(), new Constraints(new Leading(63, 206, 10, 10), new Leading(85, 12, 12)));
            add(getJLabel0(), new Constraints(new Leading(16, 10, 10), new Leading(40, 12, 12)));
            add(getJLabel2(), new Constraints(new Leading(9, 10, 10), new Leading(62, 12, 12)));
            add(getJLabel3(), new Constraints(new Leading(10, 12, 12), new Leading(85, 12, 12)));
            add(getJLabel1(), new Constraints(new Leading(22, 10, 10), new Leading(16, 12, 12)));
            add(getJTextField0(), new Constraints(new Leading(62, 207, 12, 12), new Leading(13, 21, 12, 12)));
            add(getJTextField1(), new Constraints(new Leading(62, 206, 12, 12), new Leading(38, 12, 12)));
            setSize(320, 240);
        }
     
        private JLabel getJLabel1() {
            if (jLabel1 == null) {
                jLabel1 = new JLabel();
                jLabel1.setText("CIN");
            }
            return jLabel1;
        }
     
        private JLabel getJLabel3() {
            if (jLabel3 == null) {
                jLabel3 = new JLabel();
                jLabel3.setText("adresse");
            }
            return jLabel3;
        }
     
        private JLabel getJLabel2() {
            if (jLabel2 == null) {
                jLabel2 = new JLabel();
                jLabel2.setText("prénom");
            }
            return jLabel2;
        }
     
        private JTextField getJTextField3() {
            if (jTextField3 == null) {
                jTextField3 = new JTextField();
            }
            return jTextField3;
        }
     
        private JTextField getJTextField2() {
            if (jTextField2 == null) {
                jTextField2 = new JTextField();
            }
            return jTextField2;
        }
     
        private JTextField getJTextField1() {
            if (jTextField1 == null) {
                jTextField1 = new JTextField();
            }
            return jTextField1;
        }
     
        private JLabel getJLabel0() {
            if (jLabel0 == null) {
                jLabel0 = new JLabel();
                jLabel0.setText("nom");
            }
            return jLabel0;
        }
     
        private JButton getJButton0() {
            if (jButton0 == null) {
                jButton0 = new JButton();
                jButton0.setText("ok");
                jButton0.addMouseListener(new MouseAdapter() {
     
                    public void mouseClicked(MouseEvent event) {
                        jButton0MouseMouseClicked(event);
    try {
    Class.forName("com.mysql.jdbc.Driver");
    System.out.println("Driver O.K.");
     
    String url = "jdbc:mysql://localhost/client 2"; 
     String login = "root";
     String passwd = "";
     
    Connection conn = DriverManager.getConnection(url,login, passwd);
    System.out.println("Connexion effective !");
     
    //Création d'un objet Statement
    Statement state = conn.createStatement();
    //L'objet ResultSet contient le résultat de la requête SQL
     
    state.executeUpdate("INSERT INTO information(CIN,nom,prénom,adresse) VALUES(('+JTxtField0.getText()+','+JtextField1.getText()+','+JtxtFiled2 .getText()+','+JtxtFiled.getText()+')");                                        
     
     
    } catch (Exception e) {
    e.printStackTrace();}
                    }
                });
            }
            return jButton0;
        }
     
        private JTextField getJTextField0() {
            if (jTextField0  == null) {
                jTextField0 = new JTextField();
                jTextField0.setToolTipText("TextCIN");
            }
            return jTextField0;
        }
     
        private static void installLnF() {
            try {
                String lnfClassname = PREFERRED_LOOK_AND_FEEL;
                if (lnfClassname == null)
                    lnfClassname = UIManager.getCrossPlatformLookAndFeelClassName();
                UIManager.setLookAndFeel(lnfClassname);
            } catch (Exception e) {
                System.err.println("Cannot install " + PREFERRED_LOOK_AND_FEEL
                        + " on this platform:" + e.getMessage());
            }
        }
     
        /**
         * Main entry of the class.
         * Note: This class is only created so that you can easily preview the result at runtime.
         * It is not expected to be managed by the designer.
         * You can modify it as you like.
         */
        public static void main(String[] args) {
            installLnF();
            SwingUtilities.invokeLater(new Runnable() {
                public void run() {
                    _w1 frame = new _w1();
                    frame.setDefaultCloseOperation(_w1.EXIT_ON_CLOSE);
                    frame.setTitle("_w1");
                    frame.getContentPane().setPreferredSize(frame.getSize());
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                }
            });
        }
     
        private void jButton0MouseMouseClicked(MouseEvent event) {
        }
    }
    Erreur obtenue :
    com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Erreur de syntaxe près de '' à la ligne 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
    at java.lang.reflect.Constructor.newInstance(Unknown Source)
    at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
    at com.mysql.jdbc.Util.getInstance(Util.java:386)
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1052)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3609)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3541)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2002)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2163)
    at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2618)
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1749)
    at com.mysql.jdbc.StatementImpl.executeUpdate(StatementImpl.java:1666)
    at com.m1.m2._w1$1.mouseClicked(_w1.java:132)
    at java.awt.AWTEventMulticaster.mouseClicked(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$000(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.awt.EventQueue$4.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)
    Quelqu'un saurait-il m'expliquer d'où peut venir le problème ?

    Merci d'avance pour votre aide.

  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
    tu as un problème avec ta chaine de caractères.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    state.executeUpdate("INSERT INTO information(CIN,nom,prénom,adresse) VALUES(('+JTxtField0.getText()+','+JtextField1.getText()+','+JtxtFiled2 .getText()+','+JtxtFiled.getText()+')");

    pour concaténer 2 chaines en Java c'est
    "A" + "B"

    De plus tu devrais préferrer un prepared statement pour faire ton insert, ça sera plus performant et plus sûr également.

    Il faut aussi que tu penses à fermer tes objest statement et conn.

    Tout cela est expliqué dans la FAQ
    6.2. Les instructions paramétrées - PreparedStatement
    Doit on fermer un Statement ?
    "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/

  3. #3
    Membre à l'essai
    Profil pro
    Réseau informatique
    Inscrit en
    Février 2012
    Messages
    27
    Détails du profil
    Informations personnelles :
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Réseau informatique
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Février 2012
    Messages : 27
    Points : 16
    Points
    16
    Par défaut
    Citation Envoyé par in Voir le message
    tu as un problème avec ta chaine de caractères.

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    state.executeUpdate("INSERT INTO information(CIN,nom,prénom,adresse) VALUES(('+JTxtField0.getText()+','+JtextField1.getText()+','+JtxtFiled2 .getText()+','+JtxtFiled.getText()+')");

    pour concaténer 2 chaines en Java c'est
    "A" + "B"

    De plus tu devrais préferrer un prepared statement pour faire ton insert, ça sera plus performant et plus sûr également.

    Il faut aussi que tu penses à fermer tes objest statement et conn.

    Tout cela est expliqué dans la FAQ
    6.2. Les instructions paramétrées - PreparedStatement
    Doit on fermer un Statement ?

    comment je peut insert dans la base de donné Mysql
    est ce que je peut utiliser plusieurs Statement

    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
    try {
    	state1 = conn.createStatement();
    .
    .
    .
    } catch (Exception e) {
    	// TODO: handle exception
    }
    try {
    	state2 = conn.createStatement();
    .
    .
    .
    } catch (Exception e) {
    	// TODO: handle exception
    }
    .
    .
    .

  4. #4
    Membre habitué
    Homme Profil pro
    Technicien maintenance
    Inscrit en
    Mai 2008
    Messages
    382
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 39
    Localisation : France, Loire (Rhône Alpes)

    Informations professionnelles :
    Activité : Technicien maintenance
    Secteur : Industrie

    Informations forums :
    Inscription : Mai 2008
    Messages : 382
    Points : 191
    Points
    191
    Par défaut
    Citation Envoyé par XMMMX Voir le message
    comment je peut insert dans la base de donné Mysql
    est ce que je peut utiliser plusieurs Statement
    Non.
    Ce qui ne va pas c'est la concaténation dans ta requête.
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    state.executeUpdate("INSERT INTO information(CIN,nom,prénom,adresse) VALUES(('"+JTxtField0.getText()+"','"+JtextField1.getText()+"','"+JtxtFiled2 .getText()+"','"+JtxtFiled.getText()+"')");

Discussions similaires

  1. Eclipse + gestion base de données
    Par fanette dans le forum Eclipse Java
    Réponses: 11
    Dernier message: 04/11/2018, 19h41
  2. Connexion à une base de donnée avec swing sous eclipse
    Par kodo dans le forum Eclipse Java
    Réponses: 3
    Dernier message: 07/04/2006, 11h03
  3. Réponses: 1
    Dernier message: 25/09/2005, 16h18
  4. [JDBC]Eclipse et base de données
    Par gigande dans le forum Eclipse Java
    Réponses: 1
    Dernier message: 15/04/2005, 14h04
  5. [base de donnée] accée a la base de données sur eclipse
    Par khalidlyon dans le forum Eclipse Java
    Réponses: 1
    Dernier message: 07/04/2005, 22h12

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