1 / 15

JDBC

JDBC. Eseguire una query String query = "SELECT * FROM COFFEES"; Statement stmt = con.createStatement (); ResultSet rs = stmt.executeQuery ( query ); while ( rs.next ()) { String s = rs.getString ("COF_NAME"); float n = rs.getFloat ("PRICE");

zuzana
Download Presentation

JDBC

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. JDBC

  2. Eseguire una query Stringquery = "SELECT * FROM COFFEES"; Statement stmt = con.createStatement(); ResultSetrs = stmt.executeQuery(query); while (rs.next()) { String s = rs.getString("COF_NAME"); float n = rs.getFloat("PRICE"); System.out.println(s + " " + n); } rs.close(); stmt.close();

  3. rs.next() sempre… query=“SELECT count(*) AS C”; rs=stmt.executeQuery(query); if (rs.next()) int m = rs.getString("C"); else System.out.println(“ahhhhhhh”); }

  4. 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 }

  5. Eseguire un update

  6. Transazioni in JDBC • Scelta della modalità delle transazioni: un metodo definito nell'interfaccia Connection: setAutoCommit(booleanautoCommit) • 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) }

  8. 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;

  9. // 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(); }

  10. /** * newConnections */privatesynchronizedvoidnewConnections() throwsException {// 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] = ""; } }

  11. /** * extendConnections */ public synchronizedvoidextendConnections() throwsException {// 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];

  12. //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; }

  13. /** getConnection - assegna una connessione all’utente who */ public synchronized Connection getConnection(Stringwho) throwsException {intindFree = findFreeConnection();if (indFree<0) { // se arriva qui, il pool è saturo: lo estende e // richiama ancora findFreeConn…()extendConnections();indFree= findFreeConnection(); if(indFree < 0 ) returnnull; // 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]; }

  14. /** getConnection */ public synchronized Connection getConnection() throwsException {returngetConnection(“noName”); }/** * releaseConnection - la connessione viene solo “liberata” */ public synchronizedvoidreleaseConnection(Connection c) { for (int i = 0; i < numCon; i++) {if (con[i] == c) {who[i] = "";busy[i] = false; } } }

  15. /** findFreeConnection - scandisce il vettore e restituisce l’indice */protectedintfindFreeConnection() { for(int i = 0; i < numCon; i++)if ( ! busy[i] ) return i;return -1; }/** printStatusConnection */ public StringprintStatusConnection() { Stringresult = ""; for (int i = 0; i < numCon; i++) result += "Conn. " + i + ": " + busy[i] + " used by: " + who[i]; returnresult; } } // chiude la classe

More Related