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
| package gestionBdd;
import java.util.List;
import java.util.Properties;
import java.util.Vector;
import org.apache.commons.dbcp.BasicDataSource;
//import org.apache.log4j.Logger;
import java.sql.*;
//* importer les packages dans le rep lib:
//* commons-pool-1.3.jar
//* commons-dbcp-1.2.2.jar
//* et le driver JDBC
//* Appel connexion
//* Connection con = null;
//* con = Pool_de_connexion.getConnection();
//* con.Close()
//* le fichier dbcp.properties est à placer sur la racine de www
//* c à d au même niveau que www
//* contenu de dbcp.properties
//* urlBdd=jdbc:mysql://127.0.0.1:3306/demo
//* login=root
//* password=
//* driver=com.mysql.jdbc.Driver
//* nb_connection=5
//* tps_max=50
public class PoolDeConnexion {
public static BasicDataSource bds;
public PoolDeConnexion(){}
// static Logger logger = Logger.getLogger(PoolDeConnexion.class);
//initialisation du pool
public static Boolean initialise(final Properties p)
{
bds = new BasicDataSource();
bds.setDriverClassName(p.getProperty("driver"));
bds.setUrl(p.getProperty("urlBdd")+"?autoReconnect=true&jdbcCompliantTruncation=false");
bds.setUsername(p.getProperty("login"));
bds.setPassword(p.getProperty("password"));
bds.setInitialSize(Integer.parseInt(p.getProperty("nb_connection"))); //taille du pool
bds.setMaxWait(Integer.parseInt(p.getProperty("tps_max"))); //tps d'attente max
bds.setValidationQuery("SELECT 1"); //rqte de validation
bds.setTimeBetweenEvictionRunsMillis(200);
bds.setTestWhileIdle(true);
bds.setTestOnBorrow(true);
//à strapper une fois tout ok
index.GestMat.paramconnexion = p.getProperty("urlBdd")+"-"+p.getProperty("login")+"-"+p.getProperty("password");
return(true);
}
/**
* Retourne une connexion<br />
* @return
*/
public static Connection getConnection(){
try{
//index.GestMat.tabConn.add(bds.getConnection());
//return index.GestMat.tabConn.lastElement();
return bds.getConnection();
}catch(final Exception e){index.GestMat.poolDeConnexionInitialise = false;
e.printStackTrace();
String[] msg = e.getMessage().split("\\n");
if(msg.length>5)index.GestMat.trace = "--"+ msg[5];
//index.GestMat.trace = "--"+e.getMessage().toString().replaceAll("\\n", "<br />");
try{bds.close();}catch(final SQLException e1){}
return null;}
}
} |
Partager