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

avec Java Discussion :

JNDI DataSource / PreparedStatement


Sujet :

avec Java

  1. #1
    Membre à l'essai
    Homme Profil pro
    Développeur Java
    Inscrit en
    Juin 2011
    Messages
    18
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2011
    Messages : 18
    Points : 16
    Points
    16
    Par défaut JNDI DataSource / PreparedStatement
    Bonjour,

    Pouvez vous m'aider à executer un Query à l'aide PreparedStatement sachant que ma connexion passe par une DataSource JNDI.

    Context.xml

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    <?xml version="1.0" encoding="UTF-8"?>
    <Context>
        <!-- Specify a JDBC datasource -->
     
    <Resource name="jdbc/TestDB" auth="Container" type="javax.sql.DataSource"
                   maxActive="100" maxIdle="30" maxWait="10000"
                   username="root" password="admin" driverClassName="com.mysql.jdbc.Driver"
                   url="jdbc:mysql://localhost:3306/myfirstdb"/>
     
    </Context>





    La Classe ConnexionBDD qui Fonctionne tres bien

    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
    package interactiondb;
     
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.util.logging.Level;
    import java.util.logging.Logger;
     
    import javax.sql.DataSource;
    import javax.naming.Context;
    import javax.naming.InitialContext;
    import javax.naming.NamingException;
     
    import com.mysql.jdbc.PreparedStatement;
     
     
     
     
    public class ConnexionBDD 
    {
     
    	private static Connection connexion;
    	static DataSource dataSource=null;
    	public Context ctx;
     
    	public ConnexionBDD() 
    	{
     
     
    		this.connexion = null;
     
     
    		try 
    		{
     
     
    			ctx = new InitialContext();
    			dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/TestDB");
     
     
     
    		} 
    		catch (NamingException e) 
    		{
    		// TODO Auto-generated catch block
    		e.printStackTrace();
    		}
     
     
    	}
     
     
    	public Connection getConnexion() 
    	{
     
    		try 
    		{
     
    			connexion= dataSource.getConnection();
    		} 
    		catch (SQLException e) 
    		{
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
     
    		return this.connexion;
    	}
     
     
    }




    Et enfin la classe CRUD

    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
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    package interactiondb;
     
    import java.sql.ResultSet;
    import java.sql.SQLException;
     
    import com.mysql.jdbc.Connection;
    import com.mysql.jdbc.PreparedStatement;
    import java.util.logging.Logger;
    import java.util.logging.Level;
     
     
    import model.Employees;
    //import model.Member;
    import interactiondb.ConnexionBDD;
     
    public class CRUD 
     
    {
     
    	ConnexionBDD connect = new ConnexionBDD();
    	Connection con=null;
    	PreparedStatement pstmt;
     
     
    	public CRUD ()
    	{
     
    		System.out.println("Etape 1");
     
    		con = (Connection) connect.getConnexion();
     
    		System.out.println("Etape 2");
     
     
    	}
     
    	// A Verifier
     
    	public int login(String login, String password)
    	{
     
    		int count=0;
     
    		try 
    		{
     
    			System.out.println("Etape 3");
     
    			pstmt=(PreparedStatement) con.prepareStatement("select * from member"
    					+ " where login='" + login  + "' and password='" + password  + "'");
     
    			System.out.println("Etape 4");
     
     
    			ResultSet result = pstmt.executeQuery();
     
    			System.out.println("Etape 5");
     
     
    			// Exploitation des résultats
    			while (result.next()) 
    			{
    				count++;
    			}
    		} 
    		catch (Exception e) 
    		{
     
    			Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, e);
    		} 
     
    		try 
    		{
    			pstmt.close();
    		} 
    		catch (SQLException e) 
    		{
    			Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, e);
    		}
    		return count;
     
     
    	}
     
    	/////////////////////////////
     
     
    	public Employees edit(int matricola)
    	{
     
    		Employees listemployees = null;
     
    		try 
    		{
    			pstmt=(PreparedStatement) con.prepareStatement("select * from employees"
    					+ " where matricola='" + matricola  + "'");
    			ResultSet result = pstmt.executeQuery();
     
    			// Exploitation des résultats
    			while (result.next()) 
    			{
    				listemployees = new Employees(result.getInt("matricola"),result.getString("dataas"),result.getString("nome"),result.getString("cognome"),result.getString("datafa"));                                            //////////////////////
    			}
    		} 
    		catch (Exception e) 
    		{
     
    			Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, e);
    		} 
     
    		try 
    		{
    			pstmt.close();
    		} 
    		catch (SQLException e) 
    		{
    			Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, e);
    		}
    		return listemployees;
     
     
    	}
     
     
     
     
     
    	public int delete(int matricola) throws SQLException
    	{
    		int resultat=0;
     
    		try 
    		{
     
    			pstmt=(PreparedStatement) con.prepareStatement("delete from 'employees' where 'matricola'="+ matricola);
    			resultat = pstmt.executeUpdate();
     
     
    		} 
    		catch (Exception e) 
    		{
     
    			Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, e);
    		} 
     
    		try 
    		{
    			pstmt.close();
    		} 
    		catch (SQLException e) 
    		{
    			Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, e);
    		}
     
    		return resultat;
    	}
     
     
    	public int update(Employees employee) throws SQLException
    	{
     
    		int resultat=0;
     
    		Employees emp = new Employees(employee.getmatricola(),employee.getdataas(),employee.getnome(),employee.getcognome(),employee.getdatafa());
    		try 
    		{
    			pstmt=(PreparedStatement) con.prepareStatement("UPDATE employees SET dataas = '" + emp.getdataas() + "', nome = '" + emp.getnome() + "', cognome = '" + emp.getcognome() + "', datafa = '" + emp.getdatafa() + "' WHERE matricola = '" + emp.getmatricola() + "'");
    			resultat = pstmt.executeUpdate();
     
     
    		} 
    		catch (Exception e) 
    		{
     
    			Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, e);
    		} 
     
     
     
    		try 
    		{
    			pstmt.close();
    		} 
    		catch (SQLException e) 
    		{
    			Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, e);
    		}
     
    		return resultat;
     
    	}
     
    	public int insert(Employees p) throws SQLException
    	{
     
    		int resultat=0;
     
    		try 
    		{
    			pstmt=(PreparedStatement) con.prepareStatement("INSERT INTO employees(matricola,dataas,nome,cognome,datafa) " +
        "VALUES (" + p.getmatricola() + ", '" + p.getdataas() + "', '" + p.getnome() + "', '" + p.getcognome() + "','" + p.getdatafa() + "')");
    			resultat = pstmt.executeUpdate();
     
     
    		} 
    		catch (Exception e) 
    		{
     
    			Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, e);
    		} 
     
    		try 
    		{
    			pstmt.close();
    		} 
    		catch (SQLException e) 
    		{
    			Logger.getLogger(CRUD.class.getName()).log(Level.SEVERE, null, e);
    		}
     
    		return resultat;
     
    	}
     
     
    }

  2. #2
    Rédacteur/Modérateur
    Avatar de andry.aime
    Homme Profil pro
    Inscrit en
    Septembre 2007
    Messages
    8 391
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Ile Maurice

    Informations forums :
    Inscription : Septembre 2007
    Messages : 8 391
    Points : 15 059
    Points
    15 059
    Par défaut
    Bonsoir,

    Quand tu utilises un PreparedStatement, ne met pas les valeurs en dur dans la requête(et c'est ce qu'on évite de faire d'où l'utilisation de PreparedStatement)
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    PreparedStatement pstmt=(PreparedStatement) con.prepareStatement("select * from member where login=? and password=?");
    pstmt.setString(1, login);
    pstmt.setString(2, password);
    A+.

  3. #3
    Membre à l'essai
    Homme Profil pro
    Développeur Java
    Inscrit en
    Juin 2011
    Messages
    18
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2011
    Messages : 18
    Points : 16
    Points
    16
    Par défaut
    Le code fonctionnait très bien lorsque j'utilisais une connexion avec un Driver et non un jndi. La classe CRUD fonctionnait a merveille. Maintenant depuis que j'utilise un JNDI DataSource, la classe crud ne fonctionne plus et l'erreur se produit lors de l'execution de la ligne suivante:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    con = (Connection) connect.getConnexion();

    Et L'erreur est la suivante


    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
    Etape 1
    27-ott-2011 16.24.43 org.apache.catalina.core.StandardWrapperValve invoke
    GRAVE: Servlet.service() for servlet Controller threw exception
    java.lang.ClassCastException: org.apache.tomcat.dbcp.dbcp.PoolingDataSource$PoolGuardConnectionWrapper cannot be cast to com.mysql.jdbc.Connection
    	at interactiondb.CRUD.<init>(CRUD.java:30)
    	at control.Controller.processRequest(Controller.java:121)
    	at control.Controller.doPost(Controller.java:294)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
    	at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
    	at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    	at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    	at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
    	at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
    	at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    	at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    	at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    	at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:291)
    	at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:859)
    	at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:602)
    	at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
    	at java.lang.Thread.run(Thread.java:662)

  4. #4
    Expert éminent sénior
    Avatar de sinok
    Profil pro
    Inscrit en
    Août 2004
    Messages
    8 765
    Détails du profil
    Informations personnelles :
    Âge : 43
    Localisation : France, Paris (Île de France)

    Informations forums :
    Inscription : Août 2004
    Messages : 8 765
    Points : 12 977
    Points
    12 977
    Par défaut
    Il ne faut jamais faire des imports des classes fournies par le driver JDBC.

    Ceux qu'il faut importer sont les classes issues du java.sql et surtout pas depuis le package com.mysql.jdbc
    Hey, this is mine. That's mine. All this is mine. I'm claiming all this as mine. Except that bit. I don't want that bit. But all the rest of this is mine. Hey, this has been a really good day. I've eaten five times, I've slept six times, and I've made a lot of things mine. Tomorrow, I'm gonna see if I can't have sex with something.

  5. #5
    Membre à l'essai
    Homme Profil pro
    Développeur Java
    Inscrit en
    Juin 2011
    Messages
    18
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Tunisie

    Informations professionnelles :
    Activité : Développeur Java
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Juin 2011
    Messages : 18
    Points : 16
    Points
    16
    Par défaut JNDI Data Source / Prepared Statement Resolu
    Citation Envoyé par sinok Voir le message
    Il ne faut jamais faire des imports des classes fournies par le driver JDBC.

    Ceux qu'il faut importer sont les classes issues du java.sql et surtout pas depuis le package com.mysql.jdbc
    Le problème est resolu!!! Il fallait remplacer les import suivant:

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    import com.mysql.jdbc.Connection;
    import com.mysql.jdbc.PreparedStatement;
    par les import

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    import java.sql.Connection;
    import java.sql.PreparedStatement;

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

Discussions similaires

  1. [Serveur Weblogic] Changement JNDI Datasource
    Par Koko313 dans le forum Développement Web en Java
    Réponses: 0
    Dernier message: 13/10/2011, 11h42
  2. [JNDI][DATASOURCES] jdbc -> datasources
    Par mlequim dans le forum JDBC
    Réponses: 6
    Dernier message: 15/04/2009, 09h58
  3. Problème nom JNDI + datasource
    Par javasmif dans le forum Weblogic
    Réponses: 1
    Dernier message: 11/12/2007, 11h13
  4. Problème nom JNDI pour Datasource
    Par Nysmensys dans le forum JOnAS
    Réponses: 2
    Dernier message: 22/03/2007, 09h29
  5. [Datasource] [JNDI] Problème de nommage
    Par legzo dans le forum Wildfly/JBoss
    Réponses: 5
    Dernier message: 29/01/2007, 15h37

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