Précédent   Forum des professionnels en informatique > Java > Général Java > JDBC
JDBC Forum d'entraide sur l'API JDBC (Java Database Connectivity) et l'accès aux bases de données. Avant de poster -> FAQ JDBC
Partagez cette discussion sur d'autres réseaux sociaux : Viadeo Twitter Google Facebook Digg Delicious MySpace Yahoo
Réponse Proposer ce sujet en actualité
 
Outils de la discussion
Publicité
'
Vieux 11/01/2012, 12h35   #1
Membre habitué
 
Inscription : mai 2008
Messages : 285
Détails du profil
Informations personnelles :
Âge : 27
Localisation : France, Loire (Rhône Alpes)

Informations forums :
Inscription : mai 2008
Messages : 285
Points : 111
Points : 111
Par défaut Timeout MySQL au bout de 8 heures

Bonjour à tous,

J'utilise JDBC, pour me connecter a MYSQL.
Mais seulement voilà, J'ai au bout de 8 heures d'ouverture de connection un timeout qui me provoque une erreur:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet successfully received from the server was 45 496 828 milliseconds ago.
The last packet sent successfully to the server was 1 milliseconds ago.

le Wait Time out est configuré:
wait timeout : 28 800
Equivalent de 8heures.

Grosso-modo, j'ouvre la connexion et je ne la referme jamais.
Car si je la ferme et la ré-ouvre a chaque requête, j'ai l'erreur: "too many connections"

Voici mon code:
JdbcConnector
Code :
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
public class JdbcConnector {
	static Logger logger = Logger.getLogger("JdbcConnector.class");
	private static Connection connect;
 
	/**
	 * Méthode qui va retourner notre instance
	 * et la créer si elle n'existe pas...
	 * @return
	 */
	public static Connection getInstance(){
		try {
			if(connect == null || connect.isClosed()){
				try {
					//On regarde les préférences:
					Serializer<Preferences> preferences = new Serializer<Preferences>(new File("file/Pito.lic"));
					preferences.lectureserialize();
					Serializer<Licence> licence = new Serializer<Licence>(new File("file/sack.lic"));
					licence.lectureserialize();
					String serveur=(licence.getObject()!=null && licence.getObject().getType_licence().equals("normal"))?"localhost":preferences.getObject().getServeur();
					if(preferences.getFile().length() > 0 && preferences.getObject().isConnection_bdd()){
						logger.info("Lecture Préférence: "+preferences.getObject().toString());
						Properties props = new Properties();
						props.setProperty("user",preferences.getObject().getUtilisateur());
						props.setProperty("password",preferences.getObject().getPassword());
						props.setProperty("autoReconnect", "true");
						connect = DriverManager.getConnection("jdbc:mysql://"+serveur+"/"+preferences.getObject().getBase(),props);
						logger.info("Connection a la base de donnée: "+connect);
					}
					else{
						connect=null;
						JOptionPane.showMessageDialog(null, "Impossible de se connecter!", "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
					}
				} catch (SQLException e) {
					JOptionPane.showMessageDialog(null, e.getMessage(), "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
				}
			}
		} catch (HeadlessException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.getMessage(), "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
		} catch (SQLException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.getMessage(), "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
		}
		return connect;	
	}
 
	public static void test_connection(String serveur, String base, String utilisteur, String passe) {
		// TODO Auto-generated method stub
		try {
			connect = DriverManager.getConnection("jdbc:mysql://"+serveur+"/"+base, utilisteur, passe);
			JOptionPane.showMessageDialog(null, "La connection avec la base de donnée est réussi!", "CONNECTION A LA BASE MYSL AVEC SUCCES! ", JOptionPane.INFORMATION_MESSAGE);
		} catch (HeadlessException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.getMessage(), "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
		} catch (SQLException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.getMessage(), "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
		}
 
	}
 
}
Classe MembresDao extends DAO<Membres>
Code :
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
public ArrayList<Membres> select(String champ, String valeur, int admin) {
		connect= JdbcConnector.getInstance();
		try {
			Statement state = this.connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
	            PreparedStatement prepare = this.connect.prepareStatement(
	            		"SELECT m.id, m.nom, m.prenom, m.passe, m.solde, m.afficher, m.admin, m.forfait "+
	            		"FROM membres m " +
	            		"WHERE `"+champ+"`=? " +
	            		"ORDER BY m.nom, m.prenom ASC");
 
	            //On paramètre notre requête préparée
	            prepare.setString(1, valeur);
 
		//On exécute la requête
		ResultSet resultat = prepare.executeQuery();
		int i=0;
		while(resultat.next()){
			table.add(i, new Membres(resultat.getInt("m.id"), resultat.getString("m.nom"), resultat.getString("m.prenom"), resultat.getString("m.passe"), 
							resultat.getFloat("m.solde"), resultat.getInt("m.afficher"), resultat.getInt("m.admin"), resultat.getInt("m.forfait")));
			i++;
		}
 
		prepare.close();
   	 	state.close();
 
		} catch (SQLException e) {
			e.printStackTrace();
	    }
		return table;
	}
Je vous remercie pour vos réponses
peofofo est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 11/01/2012, 18h36   #2
Modérateur
 
Avatar de sinok
 
Inscription : août 2004
Messages : 8 227
Détails du profil
Informations personnelles :
Âge : 32
Localisation : France, Paris (Île de France)

Informations forums :
Inscription : août 2004
Messages : 8 227
Points : 10 910
Points : 10 910
Utiliser un pool de connexions (tel que DBCP) et relâcher systématiquement les connexion en faisant un close des éléments (connexion+resultset+statement) dans le bloc finally correspondant au try/catch de tes opérations SQL.
__________________
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.
sinok est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 14/01/2012, 10h16   #3
Membre habitué
 
Inscription : mai 2008
Messages : 285
Détails du profil
Informations personnelles :
Âge : 27
Localisation : France, Loire (Rhône Alpes)

Informations forums :
Inscription : mai 2008
Messages : 285
Points : 111
Points : 111
Merci Sinok pour la réponse,

J'ai télécharger les bibliothèque et testé le code d'exemple:
http://svn.apache.org/viewvc/commons...va?view=markup

En modifiant la classe de l'exemple, ça me donne:
Code :
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
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.SQLException;
 
//
// Here are the dbcp-specific classes.
// Note that they are only used in the setupDriver
// method. In normal use, your classes interact
// only with the standard JDBC API
//
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool;
import org.apache.commons.dbcp.ConnectionFactory;
import org.apache.commons.dbcp.PoolingDriver;
import org.apache.commons.dbcp.PoolableConnectionFactory;
import org.apache.commons.dbcp.DriverManagerConnectionFactory;
 
//
// Here's a simple example of how to use the PoolingDriver.
//
 
//
// To compile this example, you'll want:
//  * commons-pool-1.5.6.jar
//  * commons-dbcp-1.3.jar (JDK 1.4-1.5) or commons-dbcp-1.4 (JDK 1.6+)
// in your classpath.
//
// To run this example, you'll want:
//  * commons-collections.jar
//  * commons-pool-1.5.6.jar
//  * commons-dbcp-1.3.jar (JDK 1.4-1.5) or commons-dbcp-1.4 (JDK 1.6+)
//  * the classes for your (underlying) JDBC driver
// in your classpath.
//
// Invoke the class using two arguments:
//  * the connect string for your underlying JDBC driver
//  * the query you'd like to execute
// You'll also want to ensure your underlying JDBC driver
// is registered.  You can use the "jdbc.drivers"
// property to do this.
//
// For example:
//  java -Djdbc.drivers=oracle.jdbc.driver.OracleDriver \
//       -classpath commons-pool-1.5.6.jar:commons-dbcp-1.4.jar:oracle-jdbc.jar:. \
//       PoolingDriverExample \
//       "jdbc:oracle:thin:scott/tiger@myhost:1521:mysid" \
//       "SELECT * FROM DUAL"
//
public class PoolingDriverExample {
 
    public static void main(String[] args) {
        //
        // First we load the underlying JDBC driver.
        // You need this if you don't use the jdbc.drivers
        // system property.
        //
        System.out.println("Loading underlying JDBC driver.");
        try {
            Class.forName("org.gjt.mm.mysql.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        System.out.println("Done.");
 
        //
        // Then we set up and register the PoolingDriver.
        // Normally this would be handled auto-magically by
        // an external configuration, but in this example we'll
        // do it manually.
        //
        System.out.println("Setting up driver.");
        try {
            setupDriver(args[0]);
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("Done.");
 
        //
        // Now, we can use JDBC as we normally would.
        // Using the connect string
        //  jdbc:apache:commons:dbcp:example
        // The general form being:
        //  jdbc:apache:commons:dbcp:<name-of-pool>
        //
 
        Connection conn = null;
        Statement stmt = null;
        ResultSet rset = null;
 
        try {
            System.out.println("Creating connection.");
			conn = DriverManager.getConnection("jdbc:mysql://localhost/bcsg", "peofofo", "test");
            System.out.println("Creating statement.");
            stmt = conn.createStatement();
            System.out.println("Executing statement.");
            rset = stmt.executeQuery(args[1]);
            System.out.println("Results:");
            int numcols = rset.getMetaData().getColumnCount();
            while(rset.next()) {
                for(int i=1;i<=numcols;i++) {
                    System.out.print("\t" + rset.getString(i));
                }
                System.out.println("");
            }
        } catch(SQLException e) {
            e.printStackTrace();
        } finally {
            try { if (rset != null) rset.close(); } catch(Exception e) { }
            try { if (stmt != null) stmt.close(); } catch(Exception e) { }
            try { if (conn != null) conn.close(); } catch(Exception e) { }
        }
 
        // Display some pool statistics
        try {
            printDriverStats();
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        // closes the pool
        try {
            shutdownDriver();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public static void setupDriver(String connectURI) throws Exception {
        //
        // First, we'll create a ConnectionFactory that the
        // pool will use to create Connections.
        // We'll use the DriverManagerConnectionFactory,
        // using the connect string passed in the command line
        // arguments.
        //
        ConnectionFactory connectionFactory =
            new DriverManagerConnectionFactory(connectURI,null);
 
        //
        // Next, we'll create the PoolableConnectionFactory, which wraps
        // the "real" Connections created by the ConnectionFactory with
        // the classes that implement the pooling functionality.
        //
        PoolableConnectionFactory poolableConnectionFactory =
            new PoolableConnectionFactory(connectionFactory, null, null, connectURI, false, false);
 
        //
        // Now we'll need a ObjectPool that serves as the
        // actual pool of connections.
        //
        // We'll use a GenericObjectPool instance, although
        // any ObjectPool implementation will suffice.
        //
        ObjectPool connectionPool =
            new GenericObjectPool(poolableConnectionFactory);
 
        //
        // Finally, we create the PoolingDriver itself...
        //
        Class.forName("org.apache.commons.dbcp2.PoolingDriver");
        PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
 
        //
        // ...and register our pool with it.
        //
        driver.registerPool("example",connectionPool);
 
        //
        // Now we can just use the connect string "jdbc:apache:commons:dbcp:example"
        // to access our pool of Connections.
        //
    }
 
    public static void printDriverStats() throws Exception {
        PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
        ObjectPool connectionPool = driver.getConnectionPool("example");
 
        System.out.println("NumActive: " + connectionPool.getNumActive());
        System.out.println("NumIdle: " + connectionPool.getNumIdle());
    }
 
    public static void shutdownDriver() throws Exception {
        PoolingDriver driver = (PoolingDriver) DriverManager.getDriver("jdbc:apache:commons:dbcp:");
        driver.closePool("example");
    }
}
Mais dans la console, j'ai encore des erreurs lié a l'argument du main:
Code :
1
2
3
4
5
6
7
8
9
10
11
Loading underlying JDBC driver.
Done.
Setting up driver.
java.lang.ArrayIndexOutOfBoundsException: 0
Done.
Creating connection.
	at PoolingDriverExample.main(PoolingDriverExample.java:92)
Creating statement.
Executing statement.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
	at PoolingDriverExample.main(PoolingDriverExample.java:116)
Je ne vois pas trop comment ajouter ce code ensuite dans méthode getInstance() (dans le premier post)


Merci encore
peofofo est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 14/01/2012, 23h22   #4
Modérateur
 
Avatar de tchize_
 
Homme
Responsable de service informatique
Inscription : avril 2007
Messages : 16 196
Détails du profil
Informations personnelles :
Sexe : Homme
Âge : 32
Localisation : Belgique

Informations professionnelles :
Activité : Responsable de service informatique
Secteur : Service public

Informations forums :
Inscription : avril 2007
Messages : 16 196
Points : 25 344
Points : 25 344
Envoyer un message via MSN à tchize_ Envoyer un message via Skype™ à tchize_
Citation:
Envoyé par peofofo Voir le message

Grosso-modo, j'ouvre la connexion et je ne la referme jamais.
Car si je la ferme et la ré-ouvre a chaque requête, j'ai l'erreur: "too many connections"
C'est que vous vous contentez d'en ouvrir de nouvelles sas fermer les connexions.
__________________
⥀⥁ Чиз faq java, cours java, javadoc. Pensez à et
"Votre génitrice tute des pédoncules au pandémonium" (le conjurateur, 1973)
tchize_ est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 16/01/2012, 09h05   #5
Membre habitué
 
Inscription : mai 2008
Messages : 285
Détails du profil
Informations personnelles :
Âge : 27
Localisation : France, Loire (Rhône Alpes)

Informations forums :
Inscription : mai 2008
Messages : 285
Points : 111
Points : 111
Merci Tchize,

En faite si je ne ferme jamais les connections je n'ai pas l'erreur "too many connections" mais un timeout sur l'ouverture de connexion.
Par contre si je ferme sur chaque requête la connexion, sur certaines pages j'ai l'erreur "too many connections".
Sur une seule action, je peux effectuer une quinzaine de requêtes.

Je pense que la réponse de Sinok est la solution, mais je n'arrive pas faire fonctionner l'exemple de la bibliothèque de dbcp.
Et je ne comprend pas trop le principe et comment l'appliqué a mon code sur le premier post?

En vous remerciant
peofofo est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 16/01/2012, 09h59   #6
Modérateur
 
Avatar de tchize_
 
Homme
Responsable de service informatique
Inscription : avril 2007
Messages : 16 196
Détails du profil
Informations personnelles :
Sexe : Homme
Âge : 32
Localisation : Belgique

Informations professionnelles :
Activité : Responsable de service informatique
Secteur : Service public

Informations forums :
Inscription : avril 2007
Messages : 16 196
Points : 25 344
Points : 25 344
Envoyer un message via MSN à tchize_ Envoyer un message via Skype™ à tchize_
Citation:
Envoyé par peofofo Voir le message
Par contre si je ferme sur chaque requête la connexion, sur certaines pages j'ai l'erreur "too many connections".
Non, justement, si vous avez cette erreur c'est justement parceque certaines connexions restent ouvertes.
__________________
⥀⥁ Чиз faq java, cours java, javadoc. Pensez à et
"Votre génitrice tute des pédoncules au pandémonium" (le conjurateur, 1973)
tchize_ est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 16/01/2012, 11h53   #7
Membre habitué
 
Inscription : mai 2008
Messages : 285
Détails du profil
Informations personnelles :
Âge : 27
Localisation : France, Loire (Rhône Alpes)

Informations forums :
Inscription : mai 2008
Messages : 285
Points : 111
Points : 111
Actuellement, le code que j'utilise n'a aucune fermeture de connexion.
Et j'ai une condition Si connexion ouverte, on ne la ré-ouvre pas.
Ce code provoque un timeout au bout de 8 heures.
Et si je met la clause finally sur chaque requête -> fermeture de connexion , j'ai l'erreur "too many connections"
De plus le temps de chargement est multiplié par 4 voir plus.
Donc l'objectif n'est pas de faire ralentir le process.
Si tu as un code d'exemple ou je peux m'inspirer.

Encore merci
peofofo est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 16/01/2012, 12h19   #8
Modérateur
 
Avatar de sinok
 
Inscription : août 2004
Messages : 8 227
Détails du profil
Informations personnelles :
Âge : 32
Localisation : France, Paris (Île de France)

Informations forums :
Inscription : août 2004
Messages : 8 227
Points : 10 910
Points : 10 910
exemple propre de gestion des connexions JDBC


Code :
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
Connection c = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
	try {
		//On récupère la connexion de la ou elle est, drive/datasource/whatever
		c = DriverManager.getConnection("jdbc:mysql://"+serveur+"/"+preferences.getObject().getBase(),props);
		stmt = c.prepareStatement("SELECT m.id, m.nom, m.prenom, m.passe, m.solde, m.afficher, m.admin, m.forfait "+
			"FROM membres m " +
			"WHERE `"+champ+"`=? " +
			"ORDER BY m.nom, m.prenom ASC");
		prepare.setString(1, valeur);
 
		//On exécute la requête
		ResultSet resultat = prepare.executeQuery();
		int i=0;
		while(resultat.next()){
			table.add(i, new Membres(	resultat.getInt("m.id"), 
					resultat.getString("m.nom"), 
					resultat.getString("m.prenom"), 
					resultat.getString("m.passe"), 
					resultat.getFloat("m.solde"), 
					resultat.getInt("m.afficher"), 
					resultat.getInt("m.admin"), 
					resultat.getInt("m.forfait")
				)
			);
			i++;
		}
	} catch ( SQLException e) {
		e.printStacktrace();
	} finally {
		if (rs != null) {
			rs.close();
		} 
		if (stmt != null) {
			stmt.close();
		} 
		if (c != null) {
			c.close();
		} 
	}
} catch(SQLException e) {
	e.printStacktrace();
}
Cf la FAQ
__________________
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.
sinok est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 16/01/2012, 22h14   #9
Membre habitué
 
Inscription : mai 2008
Messages : 285
Détails du profil
Informations personnelles :
Âge : 27
Localisation : France, Loire (Rhône Alpes)

Informations forums :
Inscription : mai 2008
Messages : 285
Points : 111
Points : 111
Merci Sinok,

J'ai donc appliqué la clause finaly
La classe MembreDao:
Code :
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
public class MembresDao extends DAO<Membres> {
 
	public MembresDao() {
    }
 
    public boolean create(Membres obj) {
    	return false;
    }
 
	@Override
	public boolean insert(Membres obj) {
		connect= JdbcConnector.getInstance();
		try {
			try {
	   		 	state = this.connect.createStatement();
	            prepare = this.connect.prepareStatement(
	            "INSERT INTO membres VALUE (?,?,?,?,?,?,?,?)");
	            //On paramètre notre requête préparée
	            prepare.setDate(1, null);
		 		prepare.setString(2, obj.getNom());
		 		prepare.setString(3, obj.getPrenom());
		 		prepare.setString(4, obj.getPasse());
		 		prepare.setFloat(5, obj.getSolde());
		 		prepare.setInt(6, obj.getAfficher());
		 		prepare.setInt(7, obj.getAdmin());
		 		prepare.setInt(8, obj.getForfait());
		 		//On exécute la requête
		 		prepare.executeUpdate();
	   	 	} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (prepare != null) {
						prepare.close();
				} 
				if (state != null) {
					state.close();
				} 
				if (connect != null) {
					connect.close();
				} 
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
 
    public boolean delete(int id) {
    	connect= JdbcConnector.getInstance();
    	try {
			try {
	    		state = this.connect.createStatement();
	          	prepare = this.connect.prepareStatement(
	          			"DELETE FROM membres WHERE id=?");
 
	          	//On paramètre notre requête préparée
	          	prepare.setInt(1, id);
 
	          	//On exécute la requête
	          	prepare.executeUpdate();
 
	    	} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (prepare != null) {
						prepare.close();
				} 
				if (state != null) {
					state.close();
				} 
				if (connect != null) {
					connect.close();
				} 
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return false;
    }
 
    public Membres find(int id) {
        connect= JdbcConnector.getInstance();
        try {
			try {
        		state = this.connect.createStatement();
        		ligne=new Membres();
	   	 		prepare = this.connect.prepareStatement(
	   	 				"SELECT m.id, m.nom, m.prenom, m.passe, m.solde, m.afficher, m.admin, m.forfait "+
	   	 				"FROM membres m " +
	   	 				"WHERE id = ?");
 
	   	 		//On paramètre notre requête préparée
	   	 		prepare.setInt(1, id);
 
	   	 		//On exécute la requête
	   	 		ResultSet resultat = prepare.executeQuery();
 
	   	 		if(resultat.first())
	   	 			ligne = new Membres(resultat.getInt("m.id"), resultat.getString("m.nom"), resultat.getString("m.prenom"), resultat.getString("m.passe"), 
	   	 					resultat.getFloat("m.solde"), resultat.getInt("m.afficher"), resultat.getInt("m.admin"), resultat.getInt("m.forfait"));
 
 
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (prepare != null) {
						prepare.close();
				} 
				if (state != null) {
					state.close();
				} 
				if (connect != null) {
					connect.close();
				} 
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        return ligne;
    }
 
    public Membres find(String champ, String valeur) {
		// TODO Auto-generated method stub
    	return null;
    }
 
    public Membres count() {               
    	connect= JdbcConnector.getInstance();
		try {
			try {
    			state = this.connect.createStatement();
    			ligne=new Membres();
	    	 	prepare = this.connect.prepareStatement(
	    	 			"SELECT COUNT(*) FROM membres");
	    	 	//On exécute la requête
	    	 	ResultSet resultat = prepare.executeQuery();
 
	    	 	if(resultat.next())
	    	 		ligne.setNombre(resultat.getInt(1));
 
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (prepare != null) {
						prepare.close();
				} 
				if (state != null) {
					state.close();
				} 
				if (connect != null) {
					connect.close();
				} 
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return ligne;
    }
 
	@Override
	public Membres count(String champ, String valeur) {
		// TODO Auto-generated method stub
		return null;
	}
 
    public boolean update(Membres obj, int id) {
    	connect= JdbcConnector.getInstance();
    	try {
			try {
    			state = this.connect.createStatement();
	          	prepare = this.connect.prepareStatement(
	          		"UPDATE membres SET passe=?, solde=?, afficher=?, admin=?, forfait=? WHERE id=?");
 
	          	//On paramètre notre requête préparée
	          	prepare.setString(1, obj.getPasse());
		 		prepare.setFloat(2, obj.getSolde());
		 		prepare.setInt(3, obj.getAfficher());
		 		prepare.setInt(4, obj.getAdmin());
		 		prepare.setInt(5, obj.getForfait());
		 		prepare.setInt(6, id);
 
		 		//On exécute la requête
		 		prepare.executeUpdate();
 
    		} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (prepare != null) {
						prepare.close();
				} 
				if (state != null) {
					state.close();
				} 
				if (connect != null) {
					connect.close();
				} 
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	return false;
    }
 
    public boolean update(Float solde, int id, String operateur) {
    	connect= JdbcConnector.getInstance();
    	String operateur_sql = (operateur=="consommation") ? "+" : "-";
    	try {
			try {
   	 			state = this.connect.createStatement();
         		prepare = this.connect.prepareStatement(
         			"UPDATE membres SET solde=`solde`"+operateur_sql+"? WHERE id=?");
 
	         	//On paramètre notre requête préparée
		 		prepare.setFloat(1, solde);
		 		prepare.setInt(2, id);
 
		 		//On exécute la requête
		 		prepare.executeUpdate();
 
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (prepare != null) {
						prepare.close();
				} 
				if (state != null) {
					state.close();
				} 
				if (connect != null) {
					connect.close();
				} 
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
   }
 
    @Override
	public boolean update(String champ, String valeur, int id) {
    	// TODO Auto-generated method stub
		connect= JdbcConnector.getInstance();
		try {
			try {
	    		state = this.connect.createStatement();
	        	prepare = this.connect.prepareStatement(
	        		"UPDATE membres SET `"+champ+"`=? " +
	        		"WHERE `id`=?");
		        //On paramètre notre requête préparée
		        prepare.setString(1, valeur);
		        prepare.setInt(2, id);
 
			 	//On exécute la requête
			 	prepare.executeUpdate();
 
		    } catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (prepare != null) {
						prepare.close();
				} 
				if (state != null) {
					state.close();
				} 
				if (connect != null) {
					connect.close();
				} 
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
    }
 
    @Override
	public boolean update(String champ, Float valeur, int id) {
		// TODO Auto-generated method stub
		return false;
	}
 
	@Override
	public boolean update(String champ, String valeur, String champ_id, int id) {
		// TODO Auto-generated method stub
		return false;
	}
 
	@Override
    public boolean update(String champ1, String valeur1, String champ2, String valeur2, int id) {
    	// TODO Auto-generated method stub
    	return false;
    }
 
	@Override
	public ArrayList<Membres> select() {
		connect= JdbcConnector.getInstance();
		try {
			try {
				state = this.connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
	            prepare = this.connect.prepareStatement(
	            		"SELECT m.id, m.nom, m.prenom, m.passe, m.solde, m.afficher, m.admin, m.forfait "+
	            		"FROM membres m " +
	            		"ORDER BY m.nom, m.prenom ASC");
 
	            //On paramètre notre requête préparée
 
				//On exécute la requête
				ResultSet resultat = prepare.executeQuery();
				int i=0;
				while(resultat.next()){
					table.add(i, new Membres(resultat.getInt("m.id"), resultat.getString("m.nom"), resultat.getString("m.prenom"), resultat.getString("m.passe"), 
							resultat.getFloat("m.solde"), resultat.getInt("m.afficher"), resultat.getInt("m.admin"), resultat.getInt("m.forfait")));
					i++;
				}
 
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (prepare != null) {
						prepare.close();
				} 
				if (state != null) {
					state.close();
				} 
				if (connect != null) {
					connect.close();
				} 
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return table;
	}
 
	@Override
	public int id_max() {
		// TODO Auto-generated method stub
		return 0;
	}
 
	@Override
	public ArrayList<Membres> select(String champ, String valeur, int admin) {
		connect= JdbcConnector.getInstance();
		try {
			try {
				state = this.connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
	            prepare = this.connect.prepareStatement(
	            		"SELECT m.id, m.nom, m.prenom, m.passe, m.solde, m.afficher, m.admin, m.forfait "+
	            		"FROM membres m " +
	            		"WHERE `"+champ+"`=? " +
	            		"ORDER BY m.nom, m.prenom ASC");
 
	            //On paramètre notre requête préparée
	            prepare.setString(1, valeur);
 
				//On exécute la requête
				ResultSet resultat = prepare.executeQuery();
				int i=0;
				while(resultat.next()){
					table.add(i, new Membres(resultat.getInt("m.id"), resultat.getString("m.nom"), resultat.getString("m.prenom"), resultat.getString("m.passe"), 
							resultat.getFloat("m.solde"), resultat.getInt("m.afficher"), resultat.getInt("m.admin"), resultat.getInt("m.forfait")));
					i++;
				}
 
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (prepare != null) {
						prepare.close();
				} 
				if (state != null) {
					state.close();
				} 
				if (connect != null) {
					connect.close();
				} 
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return table;
	}
 
	@Override
	public ArrayList<Membres> select_groupby() {
		connect= JdbcConnector.getInstance();
		try {
			try {
				state = this.connect.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
	            prepare = this.connect.prepareStatement(
	            		"SELECT m.id, m.nom, m.prenom, m.passe, SUM(m.solde) AS nombre, m.afficher, m.admin, m.forfait "+
	            		"FROM membres m ");
 
				//On exécute la requête
				ResultSet resultat = prepare.executeQuery();
				int i=0;
 
				while(resultat.next()){
					table.add(i, new Membres(resultat.getInt("m.id"), resultat.getString("m.nom"), resultat.getString("m.prenom"), resultat.getString("m.passe"), 
							resultat.getFloat("nombre"), resultat.getInt("m.afficher"), resultat.getInt("m.admin"), resultat.getInt("m.forfait")));
					i++;
				}
 
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (prepare != null) {
						prepare.close();
				} 
				if (state != null) {
					state.close();
				} 
				if (connect != null) {
					connect.close();
				} 
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return table;
	}
 
	@Override
	public ArrayList<Membres> select_groupby(String champ, String valeur,
			int admin) {
		// TODO Auto-generated method stub
		return null;
	}
}
J'ai quand même 2 questions:
Y a t'il une méthode plus fastidieuse d'écrire une seule fois, pour toutes les requêtes :
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
try {
			try {
					//Requêtes
			} catch (SQLException e) {
				e.printStackTrace();
			} finally {
				if (prepare != null) {
						prepare.close();
				} 
				if (state != null) {
					state.close();
				} 
				if (connect != null) {
					connect.close();
				} 
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
Est ce qu'il faut oublier la méthode de pool de connexions dbcp?

Merci
EDIT> Je préfère attendre des réponses avant de modifier les 45 classes DAO.
peofofo est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 16/01/2012, 23h08   #10
Modérateur
 
Avatar de tchize_
 
Homme
Responsable de service informatique
Inscription : avril 2007
Messages : 16 196
Détails du profil
Informations personnelles :
Sexe : Homme
Âge : 32
Localisation : Belgique

Informations professionnelles :
Activité : Responsable de service informatique
Secteur : Service public

Informations forums :
Inscription : avril 2007
Messages : 16 196
Points : 25 344
Points : 25 344
Envoyer un message via MSN à tchize_ Envoyer un message via Skype™ à tchize_
LE pool permet le réutilisation des connexion (ça améliore les performance) plutot que de faire une nouvelle connexion à chaque fois.

Ensuite, dans ton code, les createStatement pour ne rien en faire, ça ne sert à rien.
__________________
⥀⥁ Чиз faq java, cours java, javadoc. Pensez à et
"Votre génitrice tute des pédoncules au pandémonium" (le conjurateur, 1973)
tchize_ est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 17/01/2012, 22h53   #11
Membre habitué
 
Inscription : mai 2008
Messages : 285
Détails du profil
Informations personnelles :
Âge : 27
Localisation : France, Loire (Rhône Alpes)

Informations forums :
Inscription : mai 2008
Messages : 285
Points : 111
Points : 111
Ok, je vais le virer le createStatement.

Pour le pool de connexion, je ne trouve que des exemples avec une datasource.
Je ne veux pas de datasource, car je n'utilise qu'une seule application en JSE.

Comment intégrer le pool au DriverManager?

Merci
peofofo est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 18/01/2012, 09h59   #12
Modérateur
 
Avatar de tchize_
 
Homme
Responsable de service informatique
Inscription : avril 2007
Messages : 16 196
Détails du profil
Informations personnelles :
Sexe : Homme
Âge : 32
Localisation : Belgique

Informations professionnelles :
Activité : Responsable de service informatique
Secteur : Service public

Informations forums :
Inscription : avril 2007
Messages : 16 196
Points : 25 344
Points : 25 344
Envoyer un message via MSN à tchize_ Envoyer un message via Skype™ à tchize_
La datasource, c'est le pool. Tu ne peux pas avoir le pool sans la datasource, c'est la même chose (enfin presque, une datasource n'est pas obligée de faire du pooling)
__________________
⥀⥁ Чиз faq java, cours java, javadoc. Pensez à et
"Votre génitrice tute des pédoncules au pandémonium" (le conjurateur, 1973)
tchize_ est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 18/01/2012, 11h32   #13
Membre habitué
 
Inscription : mai 2008
Messages : 285
Détails du profil
Informations personnelles :
Âge : 27
Localisation : France, Loire (Rhône Alpes)

Informations forums :
Inscription : mai 2008
Messages : 285
Points : 111
Points : 111
Merci tchize_

J'ai voulu faire un test et j'ai obtenu ceci:
Code :
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
public static Connection getInstance(){
		try {
			if(connect == null || connect.isClosed()){
				try {
					//On regarde les préférences:
					Serializer<Preferences> preferences = new Serializer<Preferences>(new File("file/Pito.lic"));
					preferences.lectureserialize();
					Serializer<Licence> licence = new Serializer<Licence>(new File("file/sack.lic"));
					licence.lectureserialize();
					String serveur=(licence.getObject()!=null && licence.getObject().getType_licence().equals("normal"))?"localhost":preferences.getObject().getServeur();
					if(preferences.getFile().length() > 0 && preferences.getObject().isConnection_bdd()){
 
						String base = preferences.getObject().getBase();
						String utilisteur=preferences.getObject().getUtilisateur();
						String passe=preferences.getObject().getPassword();
						System.out.println("Setting up data source.");
				        DataSource dataSource = setupDataSource("jdbc:mysql://"+serveur+"/"+base);
				        connect = dataSource.getConnection();
				        System.out.println("Done.");
					}
					else{
						connect=null;
						JOptionPane.showMessageDialog(null, "Impossible de se connecter!", "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
					}
				} catch (SQLException e) {
					JOptionPane.showMessageDialog(null, e.getMessage(), "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
				}
			}
		} catch (HeadlessException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.getMessage(), "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
		} catch (SQLException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.getMessage(), "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
		}
		return connect;	
	}
 
	public static void test_connection(String serveur, String base, String utilisteur, String passe) {
		// TODO Auto-generated method stub
		try {
			connect = DriverManager.getConnection("jdbc:mysql://"+serveur+"/"+base, utilisteur, passe);
			JOptionPane.showMessageDialog(null, "La connection avec la base de donnée est réussi!", "CONNECTION A LA BASE MYSL AVEC SUCCES! ", JOptionPane.INFORMATION_MESSAGE);
		} catch (HeadlessException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.getMessage(), "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
		} catch (SQLException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.getMessage(), "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
		}
 
	}
 
	 public static DataSource setupDataSource(String connectURI) {
	        //
	        // First, we'll create a ConnectionFactory that the
	        // pool will use to create Connections.
	        // We'll use the DriverManagerConnectionFactory,
	        // using the connect string passed in the command line
	        // arguments.
	        //
	        ConnectionFactory connectionFactory =
	            new DriverManagerConnectionFactory(connectURI,null);
 
	        //
	        // Next we'll create the PoolableConnectionFactory, which wraps
	        // the "real" Connections created by the ConnectionFactory with
	        // the classes that implement the pooling functionality.
	        //
	        PoolableConnectionFactory poolableConnectionFactory =
	            new PoolableConnectionFactory(connectionFactory, null, null, connectURI, false, false);
 
	        //
	        // Now we'll need a ObjectPool that serves as the
	        // actual pool of connections.
	        //
	        // We'll use a GenericObjectPool instance, although
	        // any ObjectPool implementation will suffice.
	        //
	        ObjectPool connectionPool =
	            new GenericObjectPool(poolableConnectionFactory);
 
	        //
	        // Finally, we create the PoolingDriver itself,
	        // passing in the object pool we created.
	        //
	        PoolingDataSource dataSource = new PoolingDataSource(connectionPool);
 
	        return dataSource;
	    }

J'ai l'erreur dans la console:
Code :
1
2
FATAL - java.lang.NullPointerException
FATAL - 	at org.apache.commons.dbcp.PoolableConnectionFactory.<init>(PoolableConnectionFactory.java:54)
Je pense que ce problème vient de la variable String: "jdbc:mysql://"+serveur+"/"+base

Ce code vient des exemples sur dbcp :
http://svn.apache.org/viewvc/commons...143885&view=co

Merci pour votre aide
peofofo est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 18/01/2012, 15h22   #14
Modérateur
 
Avatar de tchize_
 
Homme
Responsable de service informatique
Inscription : avril 2007
Messages : 16 196
Détails du profil
Informations personnelles :
Sexe : Homme
Âge : 32
Localisation : Belgique

Informations professionnelles :
Activité : Responsable de service informatique
Secteur : Service public

Informations forums :
Inscription : avril 2007
Messages : 16 196
Points : 25 344
Points : 25 344
Envoyer un message via MSN à tchize_ Envoyer un message via Skype™ à tchize_
utilise new PoolableConnectionFactory(connectionFactory) plutot que la version avec plein de paramètre. Je pense qu'il ne digère pas tes null
__________________
⥀⥁ Чиз faq java, cours java, javadoc. Pensez à et
"Votre génitrice tute des pédoncules au pandémonium" (le conjurateur, 1973)
tchize_ est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 19/01/2012, 08h33   #15
Membre habitué
 
Inscription : mai 2008
Messages : 285
Détails du profil
Informations personnelles :
Âge : 27
Localisation : France, Loire (Rhône Alpes)

Informations forums :
Inscription : mai 2008
Messages : 285
Points : 111
Points : 111
Oui c'est ce que je voulais mettre, mais ce constructeur a un seul argument, n'existe pas.
Voici la classe PoolableConnectionFactory:
Code :
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
package org.apache.commons.dbcp;
/*     */ 
/*     */ import java.sql.Connection;
/*     */ import java.sql.ResultSet;
/*     */ import java.sql.SQLException;
/*     */ import java.sql.Statement;
/*     */ import java.util.Collection;
/*     */ import java.util.Iterator;
/*     */ import org.apache.commons.pool.KeyedObjectPool;
/*     */ import org.apache.commons.pool.KeyedObjectPoolFactory;
/*     */ import org.apache.commons.pool.ObjectPool;
/*     */ import org.apache.commons.pool.PoolableObjectFactory;
/*     */ 
/*     */ public class PoolableConnectionFactory
/*     */   implements PoolableObjectFactory
/*     */ {
/* 722 */   protected volatile ConnectionFactory _connFactory = null;
/* 723 */   protected volatile String _validationQuery = null;
/* 724 */   protected volatile int _validationQueryTimeout = -1;
/* 725 */   protected Collection _connectionInitSqls = null;
/* 726 */   protected volatile ObjectPool _pool = null;
/* 727 */   protected volatile KeyedObjectPoolFactory _stmtPoolFactory = null;
/* 728 */   protected Boolean _defaultReadOnly = null;
/* 729 */   protected boolean _defaultAutoCommit = true;
/* 730 */   protected int _defaultTransactionIsolation = -1;
/*     */   protected String _defaultCatalog;
/* 736 */   protected AbandonedConfig _config = null;
/*     */   static final int UNKNOWN_TRANSACTIONISOLATION = -1;
/*     */ 
/*     */   public PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool, KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, boolean defaultReadOnly, boolean defaultAutoCommit)
/*     */   {
/*  52 */     this._connFactory = connFactory;
/*  53 */     this._pool = pool;
/*  54 */     this._pool.setFactory(this);
/*  55 */     this._stmtPoolFactory = stmtPoolFactory;
/*  56 */     this._validationQuery = validationQuery;
/*  57 */     this._defaultReadOnly = ((defaultReadOnly) ? Boolean.TRUE : Boolean.FALSE);
/*  58 */     this._defaultAutoCommit = defaultAutoCommit;
/*     */   }
/*     */ 
/*     */   public PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool, KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, Collection connectionInitSqls, boolean defaultReadOnly, boolean defaultAutoCommit)
/*     */   {
/*  73 */     this._connFactory = connFactory;
/*  74 */     this._pool = pool;
/*  75 */     this._pool.setFactory(this);
/*  76 */     this._stmtPoolFactory = stmtPoolFactory;
/*  77 */     this._validationQuery = validationQuery;
/*  78 */     this._connectionInitSqls = connectionInitSqls;
/*  79 */     this._defaultReadOnly = ((defaultReadOnly) ? Boolean.TRUE : Boolean.FALSE);
/*  80 */     this._defaultAutoCommit = defaultAutoCommit;
/*     */   }
/*     */ 
/*     */   public PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool, KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, int validationQueryTimeout, boolean defaultReadOnly, boolean defaultAutoCommit)
/*     */   {
/*  95 */     this._connFactory = connFactory;
/*  96 */     this._pool = pool;
/*  97 */     this._pool.setFactory(this);
/*  98 */     this._stmtPoolFactory = stmtPoolFactory;
/*  99 */     this._validationQuery = validationQuery;
/* 100 */     this._validationQueryTimeout = validationQueryTimeout;
/* 101 */     this._defaultReadOnly = ((defaultReadOnly) ? Boolean.TRUE : Boolean.FALSE);
/* 102 */     this._defaultAutoCommit = defaultAutoCommit;
/*     */   }
/*     */ 
/*     */   public PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool, KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, int validationQueryTimeout, Collection connectionInitSqls, boolean defaultReadOnly, boolean defaultAutoCommit)
/*     */   {
/* 118 */     this._connFactory = connFactory;
/* 119 */     this._pool = pool;
/* 120 */     this._pool.setFactory(this);
/* 121 */     this._stmtPoolFactory = stmtPoolFactory;
/* 122 */     this._validationQuery = validationQuery;
/* 123 */     this._validationQueryTimeout = validationQueryTimeout;
/* 124 */     this._connectionInitSqls = connectionInitSqls;
/* 125 */     this._defaultReadOnly = ((defaultReadOnly) ? Boolean.TRUE : Boolean.FALSE);
/* 126 */     this._defaultAutoCommit = defaultAutoCommit;
/*     */   }
/*     */ 
/*     */   public PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool, KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, boolean defaultReadOnly, boolean defaultAutoCommit, int defaultTransactionIsolation)
/*     */   {
/* 140 */     this._connFactory = connFactory;
/* 141 */     this._pool = pool;
/* 142 */     this._pool.setFactory(this);
/* 143 */     this._stmtPoolFactory = stmtPoolFactory;
/* 144 */     this._validationQuery = validationQuery;
/* 145 */     this._defaultReadOnly = ((defaultReadOnly) ? Boolean.TRUE : Boolean.FALSE);
/* 146 */     this._defaultAutoCommit = defaultAutoCommit;
/* 147 */     this._defaultTransactionIsolation = defaultTransactionIsolation;
/*     */   }
/*     */ 
/*     */   public PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool, KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, Collection connectionInitSqls, boolean defaultReadOnly, boolean defaultAutoCommit, int defaultTransactionIsolation)
/*     */   {
/* 163 */     this._connFactory = connFactory;
/* 164 */     this._pool = pool;
/* 165 */     this._pool.setFactory(this);
/* 166 */     this._stmtPoolFactory = stmtPoolFactory;
/* 167 */     this._validationQuery = validationQuery;
/* 168 */     this._connectionInitSqls = connectionInitSqls;
/* 169 */     this._defaultReadOnly = ((defaultReadOnly) ? Boolean.TRUE : Boolean.FALSE);
/* 170 */     this._defaultAutoCommit = defaultAutoCommit;
/* 171 */     this._defaultTransactionIsolation = defaultTransactionIsolation;
/*     */   }
/*     */ 
/*     */   public PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool, KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, int validationQueryTimeout, boolean defaultReadOnly, boolean defaultAutoCommit, int defaultTransactionIsolation)
/*     */   {
/* 187 */     this._connFactory = connFactory;
/* 188 */     this._pool = pool;
/* 189 */     this._pool.setFactory(this);
/* 190 */     this._stmtPoolFactory = stmtPoolFactory;
/* 191 */     this._validationQuery = validationQuery;
/* 192 */     this._validationQueryTimeout = validationQueryTimeout;
/* 193 */     this._defaultReadOnly = ((defaultReadOnly) ? Boolean.TRUE : Boolean.FALSE);
/* 194 */     this._defaultAutoCommit = defaultAutoCommit;
/* 195 */     this._defaultTransactionIsolation = defaultTransactionIsolation;
/*     */   }
/*     */ 
/*     */   public PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool, KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, int validationQueryTimeout, Collection connectionInitSqls, boolean defaultReadOnly, boolean defaultAutoCommit, int defaultTransactionIsolation)
/*     */   {
/* 212 */     this._connFactory = connFactory;
/* 213 */     this._pool = pool;
/* 214 */     this._pool.setFactory(this);
/* 215 */     this._stmtPoolFactory = stmtPoolFactory;
/* 216 */     this._validationQuery = validationQuery;
/* 217 */     this._validationQueryTimeout = validationQueryTimeout;
/* 218 */     this._connectionInitSqls = connectionInitSqls;
/* 219 */     this._defaultReadOnly = ((defaultReadOnly) ? Boolean.TRUE : Boolean.FALSE);
/* 220 */     this._defaultAutoCommit = defaultAutoCommit;
/* 221 */     this._defaultTransactionIsolation = defaultTransactionIsolation;
/*     */   }
/*     */ 
/*     */   public PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool, KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, boolean defaultReadOnly, boolean defaultAutoCommit, AbandonedConfig config)
/*     */   {
/* 243 */     this._connFactory = connFactory;
/* 244 */     this._pool = pool;
/* 245 */     this._config = config;
/* 246 */     this._pool.setFactory(this);
/* 247 */     this._stmtPoolFactory = stmtPoolFactory;
/* 248 */     this._validationQuery = validationQuery;
/* 249 */     this._defaultReadOnly = ((defaultReadOnly) ? Boolean.TRUE : Boolean.FALSE);
/* 250 */     this._defaultAutoCommit = defaultAutoCommit;
/*     */   }
/*     */ 
/*     */   public PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool, KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, boolean defaultReadOnly, boolean defaultAutoCommit, int defaultTransactionIsolation, AbandonedConfig config)
/*     */   {
/* 274 */     this._connFactory = connFactory;
/* 275 */     this._pool = pool;
/* 276 */     this._config = config;
/* 277 */     this._pool.setFactory(this);
/* 278 */     this._stmtPoolFactory = stmtPoolFactory;
/* 279 */     this._validationQuery = validationQuery;
/* 280 */     this._defaultReadOnly = ((defaultReadOnly) ? Boolean.TRUE : Boolean.FALSE);
/* 281 */     this._defaultAutoCommit = defaultAutoCommit;
/* 282 */     this._defaultTransactionIsolation = defaultTransactionIsolation;
/*     */   }
/*     */ 
/*     */   public PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool, KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, boolean defaultReadOnly, boolean defaultAutoCommit, int defaultTransactionIsolation, String defaultCatalog, AbandonedConfig config)
/*     */   {
/* 308 */     this._connFactory = connFactory;
/* 309 */     this._pool = pool;
/* 310 */     this._config = config;
/* 311 */     this._pool.setFactory(this);
/* 312 */     this._stmtPoolFactory = stmtPoolFactory;
/* 313 */     this._validationQuery = validationQuery;
/* 314 */     this._defaultReadOnly = ((defaultReadOnly) ? Boolean.TRUE : Boolean.FALSE);
/* 315 */     this._defaultAutoCommit = defaultAutoCommit;
/* 316 */     this._defaultTransactionIsolation = defaultTransactionIsolation;
/* 317 */     this._defaultCatalog = defaultCatalog;
/*     */   }
/*     */ 
/*     */   public PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool, KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, Boolean defaultReadOnly, boolean defaultAutoCommit, int defaultTransactionIsolation, String defaultCatalog, AbandonedConfig config)
/*     */   {
/* 343 */     this._connFactory = connFactory;
/* 344 */     this._pool = pool;
/* 345 */     this._config = config;
/* 346 */     this._pool.setFactory(this);
/* 347 */     this._stmtPoolFactory = stmtPoolFactory;
/* 348 */     this._validationQuery = validationQuery;
/* 349 */     this._defaultReadOnly = defaultReadOnly;
/* 350 */     this._defaultAutoCommit = defaultAutoCommit;
/* 351 */     this._defaultTransactionIsolation = defaultTransactionIsolation;
/* 352 */     this._defaultCatalog = defaultCatalog;
/*     */   }
/*     */ 
/*     */   public PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool, KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, Collection connectionInitSqls, Boolean defaultReadOnly, boolean defaultAutoCommit, int defaultTransactionIsolation, String defaultCatalog, AbandonedConfig config)
/*     */   {
/* 381 */     this._connFactory = connFactory;
/* 382 */     this._pool = pool;
/* 383 */     this._config = config;
/* 384 */     this._pool.setFactory(this);
/* 385 */     this._stmtPoolFactory = stmtPoolFactory;
/* 386 */     this._validationQuery = validationQuery;
/* 387 */     this._connectionInitSqls = connectionInitSqls;
/* 388 */     this._defaultReadOnly = defaultReadOnly;
/* 389 */     this._defaultAutoCommit = defaultAutoCommit;
/* 390 */     this._defaultTransactionIsolation = defaultTransactionIsolation;
/* 391 */     this._defaultCatalog = defaultCatalog;
/*     */   }
/*     */ 
/*     */   public PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool, KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, int validationQueryTimeout, Boolean defaultReadOnly, boolean defaultAutoCommit, int defaultTransactionIsolation, String defaultCatalog, AbandonedConfig config)
/*     */   {
/* 420 */     this._connFactory = connFactory;
/* 421 */     this._pool = pool;
/* 422 */     this._config = config;
/* 423 */     this._pool.setFactory(this);
/* 424 */     this._stmtPoolFactory = stmtPoolFactory;
/* 425 */     this._validationQuery = validationQuery;
/* 426 */     this._validationQueryTimeout = validationQueryTimeout;
/* 427 */     this._defaultReadOnly = defaultReadOnly;
/* 428 */     this._defaultAutoCommit = defaultAutoCommit;
/* 429 */     this._defaultTransactionIsolation = defaultTransactionIsolation;
/* 430 */     this._defaultCatalog = defaultCatalog;
/*     */   }
/*     */ 
/*     */   public PoolableConnectionFactory(ConnectionFactory connFactory, ObjectPool pool, KeyedObjectPoolFactory stmtPoolFactory, String validationQuery, int validationQueryTimeout, Collection connectionInitSqls, Boolean defaultReadOnly, boolean defaultAutoCommit, int defaultTransactionIsolation, String defaultCatalog, AbandonedConfig config)
/*     */   {
/* 461 */     this._connFactory = connFactory;
/* 462 */     this._pool = pool;
/* 463 */     this._config = config;
/* 464 */     this._pool.setFactory(this);
/* 465 */     this._stmtPoolFactory = stmtPoolFactory;
/* 466 */     this._validationQuery = validationQuery;
/* 467 */     this._validationQueryTimeout = validationQueryTimeout;
/* 468 */     this._connectionInitSqls = connectionInitSqls;
/* 469 */     this._defaultReadOnly = defaultReadOnly;
/* 470 */     this._defaultAutoCommit = defaultAutoCommit;
/* 471 */     this._defaultTransactionIsolation = defaultTransactionIsolation;
/* 472 */     this._defaultCatalog = defaultCatalog;
/*     */   }
/*     */ 
/*     */   public void setConnectionFactory(ConnectionFactory connFactory)
/*     */   {
/* 480 */     this._connFactory = connFactory;
/*     */   }
/*     */ 
/*     */   public void setValidationQuery(String validationQuery)
/*     */   {
/* 490 */     this._validationQuery = validationQuery;
/*     */   }
/*     */ 
/*     */   public void setValidationQueryTimeout(int timeout)
/*     */   {
/* 503 */     this._validationQueryTimeout = timeout;
/*     */   }
/*     */ 
/*     */   public synchronized void setConnectionInitSql(Collection connectionInitSqls)
/*     */   {
/* 513 */     this._connectionInitSqls = connectionInitSqls;
/*     */   }
/*     */ 
/*     */   public synchronized void setPool(ObjectPool pool)
/*     */   {
/* 521 */     if ((null != this._pool) && (pool != this._pool))
/*     */       try {
/* 523 */         this._pool.close();
/*     */       }
/*     */       catch (Exception e)
/*     */       {
/*     */       }
/* 528 */     this._pool = pool;
/*     */   }
/*     */ 
/*     */   public synchronized ObjectPool getPool()
/*     */   {
/* 536 */     return this._pool;
/*     */   }
/*     */ 
/*     */   public void setStatementPoolFactory(KeyedObjectPoolFactory stmtPoolFactory)
/*     */   {
/* 546 */     this._stmtPoolFactory = stmtPoolFactory;
/*     */   }
/*     */ 
/*     */   public void setDefaultReadOnly(boolean defaultReadOnly)
/*     */   {
/* 554 */     this._defaultReadOnly = ((defaultReadOnly) ? Boolean.TRUE : Boolean.FALSE);
/*     */   }
/*     */ 
/*     */   public void setDefaultAutoCommit(boolean defaultAutoCommit)
/*     */   {
/* 562 */     this._defaultAutoCommit = defaultAutoCommit;
/*     */   }
/*     */ 
/*     */   public void setDefaultTransactionIsolation(int defaultTransactionIsolation)
/*     */   {
/* 570 */     this._defaultTransactionIsolation = defaultTransactionIsolation;
/*     */   }
/*     */ 
/*     */   public void setDefaultCatalog(String defaultCatalog)
/*     */   {
/* 578 */     this._defaultCatalog = defaultCatalog;
/*     */   }
/*     */ 
/*     */   public Object makeObject() throws Exception {
/* 582 */     Connection conn = this._connFactory.createConnection();
/* 583 */     if (conn == null) {
/* 584 */       throw new IllegalStateException("Connection factory returned null from createConnection");
/*     */     }
/* 586 */     initializeConnection(conn);
/* 587 */     if (null != this._stmtPoolFactory) {
/* 588 */       KeyedObjectPool stmtpool = this._stmtPoolFactory.createPool();
/* 589 */       conn = new PoolingConnection(conn, stmtpool);
/* 590 */       stmtpool.setFactory((PoolingConnection)conn);
/*     */     }
/* 592 */     return new PoolableConnection(conn, this._pool, this._config);
/*     */   }
/*     */ 
/*     */   protected void initializeConnection(Connection conn) throws SQLException {
/* 596 */     Collection sqls = this._connectionInitSqls;
/* 597 */     if (conn.isClosed()) {
/* 598 */       throw new SQLException("initializeConnection: connection closed");
/*     */     }
/* 600 */     if (null != sqls) { Statement stmt = null;
/*     */       Iterator iterator;
/*     */       try {
/* 603 */         stmt = conn.createStatement();
/* 604 */         for (iterator = sqls.iterator(); iterator.hasNext(); )
/*     */         {
/* 606 */           Object o = iterator.next();
/* 607 */           if (o == null) {
/* 608 */             throw new NullPointerException("null connectionInitSqls element");
/*     */           }
/*     */ 
/* 611 */           String sql = o.toString();
/* 612 */           stmt.execute(sql);
/*     */         }
/*     */       } finally {
/* 615 */         if (stmt != null)
/*     */           try {
/* 617 */             stmt.close();
/*     */           }
/*     */           catch (Exception t)
/*     */           {
/*     */           }
/*     */       }
/*     */     }
/*     */   }
/*     */ 
/*     */   public void destroyObject(Object obj) throws Exception {
/* 627 */     if (obj instanceof PoolableConnection)
/* 628 */       ((PoolableConnection)obj).reallyClose();
/*     */   }
/*     */ 
/*     */   public boolean validateObject(Object obj)
/*     */   {
/* 633 */     if (obj instanceof Connection) {
/*     */       try {
/* 635 */         validateConnection((Connection)obj);
/* 636 */         return true;
/*     */       } catch (Exception e) {
/* 638 */         return false;
/*     */       }
/*     */     }
/* 641 */     return false;
/*     */   }
/*     */ 
/*     */   public void validateConnection(Connection conn) throws SQLException
/*     */   {
/* 646 */     String query = this._validationQuery;
/* 647 */     if (conn.isClosed()) {
/* 648 */       throw new SQLException("validateConnection: connection closed");
/*     */     }
/* 650 */     if (null != query) {
/* 651 */       Statement stmt = null;
/* 652 */       ResultSet rset = null;
/*     */       try {
/* 654 */         stmt = conn.createStatement();
/* 655 */         if (this._validationQueryTimeout > 0) {
/* 656 */           stmt.setQueryTimeout(this._validationQueryTimeout);
/*     */         }
/* 658 */         rset = stmt.executeQuery(query);
/* 659 */         if (!(rset.next()))
/* 660 */           throw new SQLException("validationQuery didn't return a row");
/*     */       }
/*     */       finally {
/* 663 */         if (rset != null)
/*     */           try {
/* 665 */             rset.close();
/*     */           }
/*     */           catch (Exception t)
/*     */           {
/*     */           }
/* 670 */         if (stmt != null)
/*     */           try {
/* 672 */             stmt.close();
/*     */           }
/*     */           catch (Exception t)
/*     */           {
/*     */           }
/*     */       }
/*     */     }
/*     */   }
/*     */ 
/*     */   public void passivateObject(Object obj) throws Exception {
/* 682 */     if (obj instanceof Connection) {
/* 683 */       Connection conn = (Connection)obj;
/* 684 */       if ((!(conn.getAutoCommit())) && (!(conn.isReadOnly()))) {
/* 685 */         conn.rollback();
/*     */       }
/* 687 */       conn.clearWarnings();
/* 688 */       if (!(conn.getAutoCommit())) {
/* 689 */         conn.setAutoCommit(true);
/*     */       }
/*     */     }
/* 692 */     if (obj instanceof DelegatingConnection)
/* 693 */       ((DelegatingConnection)obj).passivate();
/*     */   }
/*     */ 
/*     */   public void activateObject(Object obj) throws Exception
/*     */   {
/* 698 */     if (obj instanceof DelegatingConnection) {
/* 699 */       ((DelegatingConnection)obj).activate();
/*     */     }
/* 701 */     if (obj instanceof Connection) {
/* 702 */       Connection conn = (Connection)obj;
/* 703 */       if (conn.getAutoCommit() != this._defaultAutoCommit) {
/* 704 */         conn.setAutoCommit(this._defaultAutoCommit);
/*     */       }
/* 706 */       if ((this._defaultTransactionIsolation != -1) && (conn.getTransactionIsolation() != this._defaultTransactionIsolation))
/*     */       {
/* 709 */         conn.setTransactionIsolation(this._defaultTransactionIsolation);
/*     */       }
/* 711 */       if ((this._defaultReadOnly != null) && (conn.isReadOnly() != this._defaultReadOnly.booleanValue()))
/*     */       {
/* 713 */         conn.setReadOnly(this._defaultReadOnly.booleanValue());
/*     */       }
/* 715 */       if ((this._defaultCatalog == null) || (this._defaultCatalog.equals(conn.getCatalog())))
/*     */         return;
/* 717 */       conn.setCatalog(this._defaultCatalog);
/*     */     }
/*     */   }
/*     */ }
 
/* Location:           C:\Users\PEO\workspace\commons-dbcp-1.4.jar
 * Qualified Name:     org.apache.commons.dbcp.PoolableConnectionFactory
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.5.3
 */
peofofo est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 20/01/2012, 10h25   #16
Membre habitué
 
Inscription : mai 2008
Messages : 285
Détails du profil
Informations personnelles :
Âge : 27
Localisation : France, Loire (Rhône Alpes)

Informations forums :
Inscription : mai 2008
Messages : 285
Points : 111
Points : 111
Bonjour, je pense avoir trouvé la solution:

Voici mon code qui fonctionne:
Code :
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
public class JdbcConnector {
	static Logger logger = Logger.getLogger("JdbcConnector.class");
	private static Connection connect;
	private static GenericObjectPool _pool = null;
	private static DataSource ds;
 
	/**
	 * Méthode qui va retourner notre instance
	 * et la créer si elle n'existe pas...
	 * @return
	 */
	public static Connection getInstance(){
		try {
			if(connect == null || connect.isClosed()){
					//On regarde les préférences:
					Serializer<Preferences> preferences = new Serializer<Preferences>(new File("file/Pito.lic"));
					preferences.lectureserialize();
					Serializer<Licence> licence = new Serializer<Licence>(new File("file/sack.lic"));
					licence.lectureserialize();
					String serveur=(licence.getObject()!=null && licence.getObject().getType_licence().equals("normal"))?"localhost":preferences.getObject().getServeur();
					if(preferences.getFile().length() > 0 && preferences.getObject().isConnection_bdd()){
						/*logger.info("Lecture Préférence: "+preferences.getObject().toString());
						Properties props = new Properties();
						props.setProperty("user",preferences.getObject().getUtilisateur());
						props.setProperty("password",preferences.getObject().getPassword());
						props.setProperty("autoReconnect", "true");
						connect = DriverManager.getConnection("jdbc:mysql://"+serveur+"/"+preferences.getObject().getBase(),props);
						logger.info("Connection a la base de donnée: "+connect);*/
						String base = preferences.getObject().getBase();
						String utilisteur=preferences.getObject().getUtilisateur();
						String passe=preferences.getObject().getPassword();
						System.out.println("Setting up data source.");
						try {
							ds = setupDataSource("jdbc:mysql://"+serveur+"/"+base, utilisteur, passe, 30, 70);
							connect = ds.getConnection();
						} catch (Exception e) {
							e.printStackTrace();
							JOptionPane.showMessageDialog(null, e.getMessage(), "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
						}
				        System.out.println("Done.");
					}
					else{
						connect=null;
						JOptionPane.showMessageDialog(null, "Impossible de se connecter!", "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
					}
			}
		} catch (HeadlessException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.getMessage(), "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
		} catch (SQLException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.getMessage(), "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
		}
		return connect;	
	}
 
	public static void test_connection(String serveur, String base, String utilisteur, String passe) {
		// TODO Auto-generated method stub
		try {
			connect = DriverManager.getConnection("jdbc:mysql://"+serveur+"/"+base, utilisteur, passe);
			JOptionPane.showMessageDialog(null, "La connection avec la base de donnée est réussi!", "CONNECTION A LA BASE MYSL AVEC SUCCES! ", JOptionPane.INFORMATION_MESSAGE);
		} catch (HeadlessException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.getMessage(), "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
		} catch (SQLException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.getMessage(), "ERREUR DE CONNEXION ! ", JOptionPane.ERROR_MESSAGE);
		}
 
	}
 
	/**
    *
    * @param connectURI - JDBC Connection URI
    * @param username - JDBC Connection username
    * @param password - JDBC Connection password
    * @param minIdle - Minimum number of idel connection in the connection pool
    * @param maxActive - Connection Pool Maximum Capacity (Size)
    * @throws Exception
    */
   public static DataSource setupDataSource(String connectURI, 
	String username, 
	String password,
	int minIdle, int maxActive
	) throws Exception {
       //
       // First, we'll need a ObjectPool that serves as the
       // actual pool of connections.
       //
       // We'll use a GenericObjectPool instance, although
       // any ObjectPool implementation will suffice.
       //
       GenericObjectPool connectionPool = new GenericObjectPool(null);
 
       connectionPool.setMinIdle( minIdle );
       connectionPool.setMaxActive( maxActive );
 
       JdbcConnector._pool = connectionPool; 
       // we keep it for two reasons
     // #1 We need it for statistics/debugging
     // #2 PoolingDataSource does not have getPool()
     // method, for some obscure, weird reason.
 
       //
       // Next, we'll create a ConnectionFactory that the
       // pool will use to create Connections.
       // We'll use the DriverManagerConnectionFactory,
       // using the connect string from configuration
       //
       ConnectionFactory connectionFactory = 
       	new DriverManagerConnectionFactory(connectURI,username, password);
 
       //
       // Now we'll create the PoolableConnectionFactory, which wraps
       // the "real" Connections created by the ConnectionFactory with
       // the classes that implement the pooling functionality.
       //
       PoolableConnectionFactory poolableConnectionFactory =
               new PoolableConnectionFactory(
       	connectionFactory,connectionPool,null,null,false,true);
 
       PoolingDataSource dataSource = 
       	new PoolingDataSource(connectionPool);
 
       return dataSource;
   }
 
   public static void printDriverStats() throws Exception {
       ObjectPool connectionPool = JdbcConnector._pool;
       logger.info("NumActive: " + connectionPool.getNumActive());
       logger.info("NumIdle: " + connectionPool.getNumIdle());
   }
 
   /**
   *  getNumLockedProcesses - gets the 
   *  number of currently locked processes on the MySQL db
   *
   *  @return Number of locked processes
   */
   public int getNumLockedProcesses()
   {
       int num_locked_connections = 0;
       Connection con = null; 
       PreparedStatement p_stmt = null;  ResultSet rs = null;
       try
       {
           con = JdbcConnector.ds.getConnection();
           p_stmt = con.prepareStatement("SHOW PROCESSLIST");
           rs = p_stmt.executeQuery();
           while(rs.next())
           {
               if(rs.getString("State") != 
               		null && rs.getString("State").equals("Locked"))
               {
                   num_locked_connections++;
               }
           }
       }
       catch(Exception e)
       {
    	   logger.debug("Failed to get get Locked Connections - Exception: " + e.toString());
       } finally {
           try {
               rs.close();
               p_stmt.close();
               con.close();
           }  catch ( java.sql.SQLException ex) {
        	   logger.error ( ex.toString() );
           }
       }
       return num_locked_connections;
   }
 
}
Ce code vient du tutoriel: http://www.freshblurbs.com/jakarta-c...-dbcp-tutorial

J'ai cependant quelques questions:
1- A quoi correspond le min pool size et le max pool size? Valeur par défaut 30 et 70.
2- Le destructeur protected void finalize(), n'ai jamais appelé est il utile?
3- La méthode printDriverStats() donne le nombre de connexions?
4- La méthode getNumLockedProcesses(), je ne vois pas a quoi elle sert?

Merci

EDIT> Je viens de remarquer que le fait d'avoir fermé les requêtes, le temps moyen d'affichage d'une page est multiplié par 2 (surtout lorsque la base est distante).
peofofo est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 20/01/2012, 12h02   #17
Modérateur
 
Avatar de sinok
 
Inscription : août 2004
Messages : 8 227
Détails du profil
Informations personnelles :
Âge : 32
Localisation : France, Paris (Île de France)

Informations forums :
Inscription : août 2004
Messages : 8 227
Points : 10 910
Points : 10 910
1 - Le min pool size est le nombre de connexions instanciées par défaut, le max étant le nombre maximal de connexions instanciées en parallèle dans le pool, au delà du max, le getConnection ne fournira la connexion qu'une fois qu'un des objets Connection sera à nouveau disponible (le but est d'éviter qu'il y ait trop de connexions simultanées au niveau du SGBD).

2 - Je ne vois pas de finalize dans ton code, de quel finalize parles tu?... De plus ce n'est pas un destructeur au sens propre du terme, et quoi qu'il en soit tu n'as en java aucune assurance quant au moment de son exécution, vu que c'est le GC qui gère ça.

3- bah suffit de lire le code de la méthode...

Code :
1
2
3
4
5
 public static void printDriverStats() throws Exception {
        ObjectPool connectionPool = ConnectionManager._pool;
        LOG.info("NumActive: " + connectionPool.getNumActive());
        LOG.info("NumIdle: " + connectionPool.getNumIdle());
    }
C'est suffisamment explicite...

4 - Récupère le nombre de processes au statut locked dans ta base mysql.
__________________
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.
sinok est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 20/01/2012, 13h28   #18
Modérateur
 
Avatar de tchize_
 
Homme
Responsable de service informatique
Inscription : avril 2007
Messages : 16 196
Détails du profil
Informations personnelles :
Sexe : Homme
Âge : 32
Localisation : Belgique

Informations professionnelles :
Activité : Responsable de service informatique
Secteur : Service public

Informations forums :
Inscription : avril 2007
Messages : 16 196
Points : 25 344
Points : 25 344
Envoyer un message via MSN à tchize_ Envoyer un message via Skype™ à tchize_
Citation:
EDIT> Je viens de remarquer que le fait d'avoir fermé les requêtes, le temps moyen d'affichage d'une page est multiplié par 2 (surtout lorsque la base est distante).
Crée un transaction explicite dans ta connexion et fait explicitement le commit. Sinon t'es au bon vouloir du driver qui pourrait faire un commit ou un rollback lors du close.
__________________
⥀⥁ Чиз faq java, cours java, javadoc. Pensez à et
"Votre génitrice tute des pédoncules au pandémonium" (le conjurateur, 1973)
tchize_ est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 24/01/2012, 06h10   #19
Membre habitué
 
Inscription : mai 2008
Messages : 285
Détails du profil
Informations personnelles :
Âge : 27
Localisation : France, Loire (Rhône Alpes)

Informations forums :
Inscription : mai 2008
Messages : 285
Points : 111
Points : 111
Merci a tous les deux

Voici mes tests:
Temps de chargement des pages (changement de vue)
- la bdd en local: moins d'une seconde
- a distance sur un serveur (PC- Windows 7) wamp avec fermeture systématique des connections 4 secondes
- a distance sur un serveur (PC- Windows 7) wamp sans fermeture systématique des connections 2 secondes
-Test bdd distant sur serveur linux chez OVH: (en cours)


Test temps de connection supérieur à 8 heures:
-sans fermeture connections : timeout au bout de 8 heures
-avec fermeture connections : test en cours


Je vous tiens informé dès que j'aurais fini tous les tests.
peofofo est déconnecté   Envoyer un message privé Réponse avec citation 00
Réponse Proposer ce sujet en actualité
Outils de la discussion



Fuseau horaire GMT +2. Il est actuellement 22h51.


 
 
 
 
Partenaires

Hébergement Web