我实现了我的连接的Pool Class和try {} catch {}最终的句子。
这是游泳池:
package Util;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;
public class PoolvTiger
{
private Vector <Connection> connections = new Vector<Connection>();
protected String jdbc;
protected String servidor;
protected String usuario;
protected String password;
protected int cantCon;
private static PoolvTiger pool;
private PoolvTiger()
{
getConfiguration();
for (int i= 0; i< cantCon;i++)
connections.add(connect());
}
public static PoolvTiger getPoolConnection()
{
if (pool== null)
pool =new PoolvTiger();
return pool;
}
private Connection connect()
{
try
{
//Setear driver
Class.forName("com.mysql.jdbc.Driver");
String dbConnectString = jdbc + servidor;
Connection con = DriverManager.getConnection (dbConnectString, usuario, password);
return con;
}
catch (SQLException e)
{
System.out.println("Mensaje Error: " + e.getMessage());
System.out.println("Stack Trace: " + e.getStackTrace());
return null;
}
catch (Exception ex)
{
System.out.println("Mensaje Error: " + ex.getMessage());
System.out.println("Stack Trace: " + ex.getStackTrace());
return null;
}
}
public void getConfiguration()
{
// Carga del fichero de propiedades
try
{
//Leo los valores de configuracion
jdbc = "jdbc:mysql://";
cantCon = 20;
servidor = Props.vtiger_host+":3306/"+Props.vtiger_db;
usuario =Props.vtiger_user;
password = Props.vtiger_pass;
}
catch (Exception e)
{
System.out.println("Mensaje Error: " + e.getMessage());
System.out.println("Stack Trace: " + e.getStackTrace());
}
}
public void closeConnections()
{
for (int i=0; i<connections.size();i++)
{
try
{
connections.elementAt(i).close();
}
catch(Exception e)
{
System.out.println("Mensaje Error: " + e.getMessage());
System.out.println("Stack Trace: " + e.getStackTrace());
}
}
}
public Connection getConnection()
{
Connection c = null;
if (connections.size()>0)
c = connections.remove(0);
else
{
c = connect();
//System.out.println("EXITO");
}
return c;
}
public void realeaseConnection(Connection c)
{
connections.add(c);
}
}
这是我的usuall实现,对于UPDATES,INSERTS和SELECTS:
Connection conn=null;
try{
conn=PoolvTiger.getPoolConnection().getConnection();
PreparedStatement ps = conn.prepareStatement("SELECT * FROM something");
ResultSet rs=ps.executeQuery();
PoolvTiger.getPoolConnection().realeaseConnection(conn);
}catch(Exception e){
Log.log("ERROR al validar usuario");
}finally {
PoolvTiger.getPoolConnection().realeaseConnection(conn);
}
我正在做它吗?
我注意到我不使用Pool的closeConnections()方法,我也不会关闭任何东西,但我的应用程序工作得很好......
结果集和语句是否也必须关闭?
要添加,我使用这种格式的大量方法。它不仅仅是一个,它们很多,所以我正在寻找完美的实现。
谢谢!