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 :

probleme avec executeupdate()


Sujet :

JDBC Java

  1. #1
    Nouveau membre du Club
    Inscrit en
    Novembre 2008
    Messages
    41
    Détails du profil
    Informations forums :
    Inscription : Novembre 2008
    Messages : 41
    Points : 30
    Points
    30
    Par défaut probleme avec executeupdate()
    bonjour,
    Je suis entrain de faire un programme java (test) sous eclipse, qui doit récupérer une trame de donnée(pas précise) , la décomposer puis la stocker dans une BD(Mysql pour mon cas)
    Tout marche bien a part l'insertion dans la base de donnée.
    En fait, Après décomposition de la trame(String) , j'insère les différentes chaine de caractères dans un tableau String!!
    voila le 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
    package conn;
    import java.util.*;
    import java.sql.*;
     
     
     
    public class Trame
    {String s;
    Connection 	conn;
    Statement stmt;
    String Tab[] = new String[10]; //tableau des valeurs
     
    	Trame() {}
    	Trame(String s){this.s=s;}
    	public void decouper(String sep) throws SQLException{
     
     
    		 int i=0;
     
     
    	 StringTokenizer st =new StringTokenizer(this.s,sep);//3 séparateurs ; , et blanc
    	 while (st.hasMoreTokens()){  //boucle de lecture
    					   Tab[i]=st.nextToken();
    					   i++;
    					   }
    	 if (Tab[0].equals("$IIMWV")&&Tab[4].equals("A<CR><LF>"))
    	 {
    		 	stmt = conn.createStatement();
    	 	stmt.executeUpdate("INSERT INTO trame VALUES (Tab[0], Tab[1], Tab[2])");
     
    		System.out.println("trame complète");
    	 }
    	 else System.out.println("trame incomplete");
     
     
    			   }
    	private void printInfo(Connection c) throws Exception
    	 {
    	 	// Get meta-data about the database
    	 	DatabaseMetaData info = c.getMetaData();
    		System.out.println("\nConnected to :\t" + info.getURL());
    	 	System.out.println("Driver :\t" + info.getDriverName());
    		System.out.println("Version :\t" + info.getDriverVersion());
    	 }
     
    	/* Print stdout all pending SQLWarning warnings
    	 */
    	 private boolean checkForSQLWarnings(SQLWarning w)
    	 	throws SQLException
    	 {
    	 	boolean warning = false;
    		if(w != null) {
    		    warning = true;
    		    System.out.println("\n**** Warning ****\n");
     
    	         while(w != null) {
    			System.out.println("SQLState: " + w.getSQLState());
    	 	        System.out.println("Message:  " + w.getMessage());
    			System.out.println("Vendor:   " + w.getErrorCode());
    	         	System.out.println("");
    	         	w = w.getNextWarning();
    	         }
    	     }
    		return warning;
    	 }
     
    	 /* Print stderr all pending SQLException exceptions
    	 */
    	 private void printSQLErrors(SQLException e)
    	 {
    	     while(e != null) {
    		    System.err.println("SQLState: " + e.getSQLState());
    	         System.err.println("Message:  " + e.getMessage());
    	         System.err.println("Vendor:   " + e.getErrorCode());
    	         System.err.println("");
    		    e = e.getNextException();
    	     }
    	 }
     
    	 public void loadDriverAndConnect()
    	 	throws Exception
    	 {
    		try {
    		    // Load the jdbc driver for MySQL
    	         Class.forName("com.mysql.jdbc.Driver");
     
    	         // Get a connection to the database source using Thin JDBC driver
    	         String url = "jdbc:mysql://localhost:3306/test";
    	         conn = DriverManager.getConnection(url, "root", "khawla");
     
    	         // Print stdout warning messages if necessary
    	         checkForSQLWarnings(conn.getWarnings());
     
    		    // Print stdout info messages
    	         printInfo(conn);
     
    	     }
    	 	catch(SQLException e) {
    		    System.err.println("\n*** SQLException caught in LoadDriver()");
    		    printSQLErrors(e);
    	         throw e;
    	     }
    	     catch(Exception e) {
    		    // This exception is caught if JDBC driver used cannot be loaded
    		    System.err.println("\n*** Exception caught in LoadDriver()");
    	         throw e;
    	     }
     
    	 }
     
    	 /**
              *     Close the connection to the data base source
              */
    	 public void close() throws Exception
    	 {
    		try {
    		    conn.close();
    	         System.out.println("Test : Disconnecting ...");
    	     }
    	     catch(Exception e) {
    		    System.err.println("\n*** Exception caught in close()");
    	         throw e;
    	     }
    	 }
     
    	 public void createTablesAndInit() throws Exception    
    	 {  
     
    	 	stmt = conn.createStatement();
    	 	stmt.executeUpdate("INSERT INTO trame VALUES ('Tab[0]', 'Tab[0]', 'Tab[0]')"); 
    	 }
     
    	 public void selectData() throws Exception    
    	 {
    	 	ResultSet rs = null;
    		String requete = "SELECT nom, pos FROM trame";
    		try{
    			rs = stmt.executeQuery(requete);	
    		}
    		catch(SQLException e){
    			System.err.println("Erreur dans selectData() - 1");
    			throw e;
    		}
     
    		while(rs.next()){
    			String s = rs.getString("nom");
    			String n = rs.getString("pos");
    			System.out.println(s + " " + n);
    		}
    	 }
     
     
    			   public static void main (String argv [])
    			    { Trame T= new Trame("$IIMWV,R,000.30,N,A<CR><LF>");
     
    			         try {
    						T.loadDriverAndConnect();
    					} catch (Exception e) {
     
    						e.printStackTrace();
    					}
    					 try {
    						T.decouper(",");
    					} catch (SQLException e) {
     
    						e.printStackTrace();
    					}
     
     
     
     
    			        }
     
    		}
     
     
     
     
     
     
    	/**
             * @param args
             */
    ET voila ce qui s'affiche sur la console:

    Connected to : jdbc:mysql://localhost:3306/test
    Driver : MySQL-AB JDBC Driver
    Version : mysql-connector-java-5.0.8 ( Revision: ${svn.Revision} )
    com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[0], Tab[1], Tab[2])' at line 1
    at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
    at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2985)
    at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1631)
    at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1723)
    at com.mysql.jdbc.Connection.execSQL(Connection.java:3277)
    at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1402)
    at com.mysql.jdbc.Statement.executeUpdate(Statement.java:1317)
    at conn.Trame.decouper(Trame.java:29)
    at conn.Trame.main(Trame.java:163)
    NB: quand j'insère des mots(String) dans executeupdate, ca marche parfaitement!!!!

  2. #2
    Nouveau membre du Club
    Inscrit en
    Novembre 2008
    Messages
    41
    Détails du profil
    Informations forums :
    Inscription : Novembre 2008
    Messages : 41
    Points : 30
    Points
    30
    Par défaut
    bonjour,
    désolée, voila le code exact, le dernier posté avait quelques erreurs!
    en tout cas , j'ai toujours le même problème avec la commande executeupdate()
    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
    package conn;
    import java.util.*;
    import java.sql.*;
     
     
     
    public class Trame
    {String s;
    Connection 	conn;
    Statement stmt;
    String Tab[] = new String[10]; //tableau des valeurs
     
    	Trame() {}
    	Trame(String s){this.s=s;}
    	public void decouper(String sep) throws SQLException{
     
     
    		 int i=0;
     
     
    	 StringTokenizer st =new StringTokenizer(this.s,sep);//3 séparateurs ; , et blanc
    	 while (st.hasMoreTokens()){  //boucle de lecture
    					   Tab[i]=st.nextToken();
    					   i++;
    					   }
    	 if (Tab[0].equals("$IIMWV")&&Tab[4].equals("A<CR><LF>"))
    	 {
    		 	stmt = conn.createStatement();
    		 	stmt.executeUpdate("INSERT INTO trame VALUES (Tab[0], Tab[1], Tab[2])"); 
     
    		System.out.println("trame complète");
    	 }
    	 else System.out.println("trame incomplete");
     
     
    			   }
    	private void printInfo(Connection c) throws Exception
    	 {
    	 	// Get meta-data about the database
    	 	DatabaseMetaData info = c.getMetaData();
    		System.out.println("\nConnected to :\t" + info.getURL());
    	 	System.out.println("Driver :\t" + info.getDriverName());
    		System.out.println("Version :\t" + info.getDriverVersion());
    	 }
     
    	/* Print stdout all pending SQLWarning warnings
    	 */
    	 private boolean checkForSQLWarnings(SQLWarning w)
    	 	throws SQLException
    	 {
    	 	boolean warning = false;
    		if(w != null) {
    		    warning = true;
    		    System.out.println("\n**** Warning ****\n");
     
    	         while(w != null) {
    			System.out.println("SQLState: " + w.getSQLState());
    	 	        System.out.println("Message:  " + w.getMessage());
    			System.out.println("Vendor:   " + w.getErrorCode());
    	         	System.out.println("");
    	         	w = w.getNextWarning();
    	         }
    	     }
    		return warning;
    	 }
     
    	 /* Print stderr all pending SQLException exceptions
    	 */
    	 private void printSQLErrors(SQLException e)
    	 {
    	     while(e != null) {
    		    System.err.println("SQLState: " + e.getSQLState());
    	         System.err.println("Message:  " + e.getMessage());
    	         System.err.println("Vendor:   " + e.getErrorCode());
    	         System.err.println("");
    		    e = e.getNextException();
    	     }
    	 }
     
    	 public void loadDriverAndConnect()
    	 	throws Exception
    	 {
    		try {
    		    // Load the jdbc driver for MySQL
    	         Class.forName("com.mysql.jdbc.Driver");
     
    	         // Get a connection to the database source using Thin JDBC driver
    	         String url = "jdbc:mysql://localhost:3306/test";
    	         conn = DriverManager.getConnection(url, "root", "khawla");
     
    	         // Print stdout warning messages if necessary
    	         checkForSQLWarnings(conn.getWarnings());
     
    		    // Print stdout info messages
    	         printInfo(conn);
     
    	     }
    	 	catch(SQLException e) {
    		    System.err.println("\n*** SQLException caught in LoadDriver()");
    		    printSQLErrors(e);
    	         throw e;
    	     }
    	     catch(Exception e) {
    		    // This exception is caught if JDBC driver used cannot be loaded
    		    System.err.println("\n*** Exception caught in LoadDriver()");
    	         throw e;
    	     }
     
    	 }
     
    	 /**
              *     Close the connection to the data base source
              */
    	 public void close() throws Exception
    	 {
    		try {
    		    conn.close();
    	         System.out.println("Test : Disconnecting ...");
    	     }
    	     catch(Exception e) {
    		    System.err.println("\n*** Exception caught in close()");
    	         throw e;
    	     }
    	 }
     
    	 public void selectData() throws Exception    
    	 {
     ResultSet rs = null;
    		String requete = "SELECT nom, pos FROM trame";
    		try{                                                    
    			rs = stmt.executeQuery(requete);	
    		}
    		catch(SQLException e){
    			System.err.println("Erreur dans selectData() - 1");
    			throw e;
    		}
     
    		while(rs.next()){
    			String s = rs.getString("nom");
    			String n = rs.getString("pos");
    			System.out.println(s + " " + n);
    		}
    	 }
     
     
    			   public static void main (String argv [])
    			    { Trame T= new Trame("$IIMWV,R,000.30,N,A<CR><LF>");
     
    			         try {
    						T.loadDriverAndConnect();
    					} catch (Exception e) {
     
    						e.printStackTrace();
    					}
    					 try {
    						T.decouper(",");
    					} catch (SQLException e) {
     
    						e.printStackTrace();
    					}
    					try {
    						T.selectData();
    					} catch (Exception e) {
     
    						e.printStackTrace();
    					}
     
     
     
     
    			        }
     
    		}
     
     
     
     
     
     
    	/**
             * @param args
             */

  3. #3
    Membre actif
    Avatar de foucha
    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    121
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 121
    Points : 251
    Points
    251
    Par défaut ce n'est pas du sql correct
    stmt.executeUpdate("INSERT INTO trame VALUES (Tab[0], Tab[1], Tab[2])");
    Il faut que tu fasses interpreter tes tab[0] par du java :

    stmt.executeUpdate("INSERT INTO trame VALUES ( " + Tab[0] + " etc
    Si ce sont des chaines de caracteres, pense aussi à mettre des ' ' autour des tab[0]. Ex : "INSERT INTO trame VALUES ('" + Tab[0] + "'"

    D'autres part, il manque la declaration des champs où tu inseres tes données, et là encore c'est une erreur SQL :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    INSERT INTO trame (champ1, champ2) VALUES (valuer1,val2);
    ++
    Foucha.
    ++
    Foucha.

    =========

    "du code propre c'est du code qui fait exactement ce qu'on croit que ça fait"

    Mes Articles DVP

  4. #4
    Expert éminent sénior
    Avatar de adiGuba
    Homme Profil pro
    Développeur Java/Web
    Inscrit en
    Avril 2002
    Messages
    13 938
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Développeur Java/Web
    Secteur : Transports

    Informations forums :
    Inscription : Avril 2002
    Messages : 13 938
    Points : 23 190
    Points
    23 190
    Billets dans le blog
    1
    Par défaut
    Salut,

    Citation Envoyé par foucha Voir le message
    Si ce sont des chaines de caracteres, pense aussi à mettre des ' ' autour des tab[0]. Ex : "INSERT INTO trame VALUES ('" + Tab[0] + "'"
    Il est préférable d'utiliser des PreparedStatements afin d'éviter les problèmes injections de code...

    a++

  5. #5
    Nouveau membre du Club
    Inscrit en
    Novembre 2008
    Messages
    41
    Détails du profil
    Informations forums :
    Inscription : Novembre 2008
    Messages : 41
    Points : 30
    Points
    30
    Par défaut
    ça marche parfaitemeeeeeeennt
    (j'avais complétement oublié la notation de tableau pour java )
    merci beaucoup pour votre aide

  6. #6
    Membre actif
    Avatar de foucha
    Profil pro
    Inscrit en
    Janvier 2009
    Messages
    121
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2009
    Messages : 121
    Points : 251
    Points
    251
    Par défaut effectivement
    avec des preparedStatement et des "?" ce serait mieux.

    Tu peux clore le fil de discussion si ton probleme est résolu?

    ++
    Foucha.
    ++
    Foucha.

    =========

    "du code propre c'est du code qui fait exactement ce qu'on croit que ça fait"

    Mes Articles DVP

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

Discussions similaires

  1. Probleme avec la copie des surfaces
    Par Black_Daimond dans le forum DirectX
    Réponses: 3
    Dernier message: 09/01/2003, 10h33
  2. Problèmes avec le filtrage des ip
    Par berry dans le forum Réseau
    Réponses: 9
    Dernier message: 30/12/2002, 07h51
  3. probleme avec la touche F10
    Par b.grellee dans le forum Langage
    Réponses: 2
    Dernier message: 15/09/2002, 22h04
  4. Probleme avec fseek
    Par Bjorn dans le forum C
    Réponses: 5
    Dernier message: 04/08/2002, 07h17
  5. [Kylix] probleme avec un imagelist
    Par NicoLinux dans le forum EDI
    Réponses: 4
    Dernier message: 08/06/2002, 23h06

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