ppt

annuncio pubblicitario
JDBC
import java.sql.*;
Connection con =
DriverManager.getConnection(
"odbc:jdbc:myDB",dbUsername,dbPswd);
con.close();
Eseguire una query
String query = "SELECT * FROM USERS";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {
String s = rs.getString("Username");
int n = rs.getInt("Age");
System.out.println(s + " " + n);
}
rs.close();
stmt.close();
rs.next() sempre…
query="SELECT count(*) AS C" +
"FROM USERS";
rs=stmt.executeQuery(query);
if (rs.next())
int m = rs.getInt("C");
else
System.out.println(“ahhhhhhh”);
}
Ogni operazione sui dati va incluso
in un blocco try catch per gestire
eventuali eccezioni
try
{ … }
catch(SQLException se)
{ //fai qualcosa }
catch(Exception e)
{ //fai qualcos’altro }
Eseguire un update
Statement stmt = con.createStatement();
stmt.executeUpdate(
"INSERT INTO USERS " +
"VALUES ("Alex", "12345", 42)");
…
stmt.close();
Transazioni in JDBC
• Scelta della modalità delle transazioni: un metodo definito nell'interfaccia
Connection:
setAutoCommit(boolean autoCommit)
• con.setAutoCommit(true)
– (default) "autocommit": ogni operazione è una transazione
• con.setAutoCommit(false)
– gestione delle transazioni da programma
con.commit()
con.rollback()
– non c'è start transaction
7
Transazioni in JDBC
try {
con.setAutoCommit(false);
Statement st=con.createStatement();
st.executeUpdate(“…”);
st.executeUpdate(“…”);
…
con.commit();
}
catch (Exception ex) {
try { con.rollback();}
catch (SQLException sqx)
}
CONNECTION POOL
import java.sql.*;
public class MyConnectionPool
{
// array di connessioni al database
Connection con[];
// array delle disponibilità delle connessioni
boolean busy[];
// registra chi sta tenendo occupata la connessione
String who[];
// numero di connessioni attive
int numCon;
// incremento dimensione del pool per accogliere nuove richieste
int inc;
// parametri di accesso al database
String dbUrl;
String dbUsername; String dbPswd;
String driverString;
/** Costruttore */
public MyConnectionPool ( String dbUrl, String dbUsername,
String dbPswd, int numCon, int inc,
String driverString )
throws Exception {
this.dbUrl
= dbUrl;
this.dbUsername = dbUsername;
this.dbPswd
= dbPswd;
this.numCon
= numCon;
this.inc
= inc;
this.driverString = driverString;
newConnections();
}
/**
* newConnections
*/
private synchronized void newConnections() throws Exception {
// alloca gli array globali (connessioni e info)
con = new Connection[numCon];
busy = new boolean[numCon];
who = new String[numCon];
Class.forName(driverString);
for (int i = 0; i < numCon; i++) {
con[i] = DriverManager.getConnection(dbUrl,dbUsername,dbPswd);
busy[i] = false;
who[i] = "";
}
}
/**
* extendConnections
*/
public synchronized void extendConnections() throws Exception {
// copia dei vecchi vettori
Connection con2[] = con;
boolean busy2[] = busy;
String who2[] = who;
// creazione dei nuovi vettori estesi
con = new Connection[numCon+inc];
busy = new boolean[numCon+inc];
who = new String[numCon+inc];
//ciclo per trasferire le vecchie connessioni nei nuovi array
for (int i = 0; i < numCon; i++) {
con[i] = con2[i];
busy[i] = busy2[i];
who[i] = who2[i];
}
//ciclo per creare le nuove connessioni da aggiungere alle precedenti
for (int i = numCon; i < numCon+inc; i++) {
con[i] = DriverManager.getConnection(dbUrl,dbUsername,dbPswd);
busy[i] = false;
who[i] = "";
}
numCon += inc;
}
/** getConnection - assegna una connessione all’utente who */
public synchronized Connection getConnection(String who)
throws Exception {
int indFree = findFreeConnection();
if (indFree < 0) {
// se arriva qui, il pool è saturo: lo estende e
// richiama ancora findFreeConn…()
extendConnections();
indFree = findFreeConnection();
if( indFree < 0 )
return null; // se arriva qui non ci sono proprio più risorse
}
// salvo catastrofi verrà sempre eseguito questo codice
busy[indFree] = true;
who[indFree] = who;
return con[indFree];
}
/** getConnection */
public synchronized Connection getConnection() throws Exception {
return getConnection(“noName”);
}
/**
* releaseConnection - la connessione viene solo “liberata”
*/
public synchronized void releaseConnection(Connection c) {
for (int i = 0; i < numCon; i++) {
if (con[i] == c) {
who[i] = "";
busy[i] = false;
}
}
}
/** findFreeConnection - scandisce il vettore e restituisce l’indice */
protected int findFreeConnection() {
for(int i = 0; i < numCon; i++)
if ( ! busy[i] )
return i;
return -1;
}
/** printStatusConnection */
public String printStatusConnection() {
String result = "";
for (int i = 0; i < numCon; i++)
result += "Conn. " + i + ": " + busy[i] + " used by: " + who[i];
return result;
}
} // chiude la classe
Scarica