






Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!







Creare un’applicazione completa JDBC Importare le classi: import java.sql.*; Usare i blocchi try … catch :
- Il primo blocco try contiene il metodo Class.forName , dal package java.lang. Questo metodo lancia un ClassNotFoundException , in maniera tale da permettere al blocco catch di gestire subito l’eccezione. - Il secondo blocco try contiene i metodi JDBC, che lanciano tutti un’eccezione del tipo SQLException , così il blocco catch può gestire solamente oggetti di quel tipo. Gestire le eccezioni try { Class.forName(“com.mysql.jdbc.Driver”); } catch (java.lang.ClassNotFoundException e) {System.err.print (“ClassNotFoundException: + e.getMessage()); } try { //il codice che genera le eccezioni SQLException vanno qui } catch (SQLException ec) { Systeem.err.println (“SQLException:” + ex.getMessage()); } Caricamento dei driver //Per un database MySQL String driver=”com.mysql.jdbc.Driver”; //Se il database è Oracle … driver=”oracle.jdbc.OracleDriver”; //Se il driver è JDBC-ODBC (tipo 1) … driver=”sun.jdbc.odbc.JdbcOdbcDriver”; //Se il database è PostgersQL … driver=”com.postgresql.Driver”; //Il metodo forName forza il caricamento del driver Class.forName (driver); //lancia una ClassNotFoundException Creazione della connessione //Per un database MySQL String url=”jdbc:mysql://localhost:3306/airdb”; //Per il database Oracle di tipo thin … url=”jdbc:oracle:thin:@//localhost:1521/airdb”; //Per il driver JDBC-ODBC (tipo 1) … url=”jdbc:odbc:aridb”;
//airdb è il DSN (Data Source Name) di solito si crea nei sistemi Windows mediante il Pannello di Controllo. //Se il database è PostGreSQL … url=”jdbc:postgresql://localhost:5432/airdb/”; //Connection è un’interfaccia, getConnection() un metodo statico della classe DriverManager Connection con=DriverManager.getConnection (url, “user”, “pwd”); //lancia una SQLException Connessione alternativa String url=”jdbc:mysql://localhost:3306/airdb?user=user&password=pwd”; Connection con=DriverManager .getConnection(url); //lancia una SQLException Preparazione dell’istruzione SQL //L’oggetto st rappresenta l’istruzione SQL //Statement è un’interfaccia Statement st=con.createStatement(); //lancia una SQLException A questo punto st esiste, ma non contiene lo statement SQL da passare al DBMS. Esecuzione della query (query di lettura) String sql=”SELECT * FROM aerei”; //ResultSet è un’interfaccia ResultSet rs=st.executeQuery(sql); //lancia una SQLException //rs contiene le righe della tabella Il cursore (puntatore al record corrente) adesso è posizionato prima della prima riga. Per spostare il cursore in avanti, indietro …, possiamo usare i seguenti metodi (booleani):
- Next(), previous(), first(), last(), beforeFirst(), afterLast(), … Elaborazione dei campi while (rs.nect()){ //modello è il nome della terza colonna della tabella String modello=rs.getString(“modello”); //posti è il nome della quinta colonna della tabella Int posti=rs.getInt(“numposti”); String produttore=rs.getString(2); //elaborazione dei campi System.out.printf(“%s%s%d\n”, modello, produttore, posti); } //fine while Chiusura degli oggetti //gli oggetti vanno chiusi correttamente nell’ordine inverso a quello di apertura. rs.close(); //ResultSet, lancia una SQLException st.close(); //Statement, lancia una SQLException con.close(); //Connection, lancia una SQLException
Query parametriche //Il? rappresenta il parametro String sql = “SELECT * FROM aerei WHERE produttore = ?”; String produttore=”boeing”; //Interfaccia PreparedStatement PreparedStatement ps=con.prepareStatement(sql); //Associamo al (primo e unico) parametro la stringa produttore ps.setString(1, produttore); //eseguiamo la query ResultSet rs=ps.executeQuery(); //nessun argomento per il metodo executeQuery, attenzione! //si possono scorrere i record while (rs.next()){ //lettura ed elaborazione dei record //… } //Il? rappresenta il parametro String sql=”SELECT * FROM aerei WHERE produttore=? AND (numposti>? OR numposti IS NULL)”; String produttore=”boeing”; int posti=100; //Interfaccia PreparedStatement PreparedStatemnt ps=con.prepareStatement (sql); //Associamo ai parametri i valori ps.setString(1, produttore); ps.setInt(2, posti); //eseguiamo la query ResultSet rs=ps.executeQuety(); //… Informazioni sulle eccezioni try { //Codice che genera l’eccezione } catch (SQLException ex){ System.out.println(“Info sulla SQLException:\n”); while (ex!= null ){ System.out.println(“Message:”+ex.getMessage()); System.out.println(“SQLState:”+ex.getSQLState()); System.out.println(“ErrorCode:”+ex.getErrorCode()); ex=ex.getNextException(); } } Informazioni sui warning Statement st=con.createStatement(); ResultSet rs=st.executeQuery(“SELECT/UPDATE/INSERT…”);
SQLWarning warning=st.getWarnings(); if (warning!=null){ System.out.println(“Info sui Warning:\n”); while (warning!=null){ System.out.println(“Message:”+warning.getMessage()); System.out.println(“SQLState:”+warning.getSQLState()); System.out.println(“ErrorCode:”+warning.getErrorCode()); warning=warning.getNextWarning(); } } Creating a Scrollable Result Set Bisogna creare un oggetto ResultSet che sia scrollable: Statement stmt=con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE , ResultSet.CONCUR_READ_ONLY);
- TYPE_FROWARD_ONLY*: creates a non-scrollable result set, (the cursor moves only forward). - TYPE_SCROLL_INSENSITIVE: does not reflect changes. - TYPES_SCROLL_SENSITIVE: reflects changes (by others). La seguente linea controlla che l’oggetto ResultSet sia scrollable: int type=rs.getType(); =default Statement stmt=con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); - CONCUR_READ_ONLY: result set è read-only; - CONCUR_UPDATE: result set è aggiornabile. ResultSet srs=stmt.executeQuery( “SELECT produttore, modello, numposti FROM aerei”) … Srs.afterLast(); while (srs.previous()){ String prod=srs.getString(“produttore”); int posti=srs.getInt(“numposti”); System.out.println(prod+” ”+posti); } Getting the Cursor Position srs.absolute(4); int rowNum=srs.getRow(); //rowNum should be 4 srs.relative(-3); rowNum=srs.getRow(); //rowNum should be 1 srs.relative(2); rowNum=srs.getRow(); //rowNum should be 3 Quattro metodi aggiuntivi permettono di verificare se il cursore è in una particolare posizione.
updateSales.executeUpdate(); … PreparedStatement updateTotal=con.prepareStatement(“UPDATE aerei SET numposti=numposti+? WHERE modello=?”); updateTotal.setInt(1, 10); updateTotal.setString(2, “AZ12”); updateTotal.executeUpdate(); con. commit (); //Committing a Transaction con. setAutoCommit (true); //Enabling Auto-commit Mode Using Transactions to Preserve Data Integrity In aggiunta agli statement di raggruppamento insieme per l’esecuzione come unità, le transazioni possono aiutare a preservare l’integrità dei dati nella tabella. Dopo aver inserito i dati vecchi, l’utente realizza che non sono più validi e chiama il metodo Connection rollback () per annullare i suoi effetti.
- Il metodo rollback abortisce una transazione e ristora i valori a cosa erano prima del tentato aggiornamento. Using Statement Objects for Batch Updates con. setAutoCommit (false); Statement stmt=con.createStatement(); stmt. addBatch (“INSERT INTO COFFEES VALUES ( ‘ Amaretto’, 49, 9.99, 0, 0)”); stmt. addBatch (“INSERT INTO COFFEES VALUES (‘Hazelnut’, 49, 9.99, 0, 0)”); stmt. addBatch (“INSERT INTO COFFEES VALUES (‘Amar Dec’, 49, 10.99, 0, 0)”); stmt. addBatch (“INSERT INTO COFFEES VALUES (‘Haze Dec’, 49, 10.99, 0, 0)”); int [] updateCounts=stmt. executeBatch (); con. commit (); con. setAutoCommit (true); Batch Update Exceptions try { //make some updates } catch (BatchUpdateException b) { System.err.println(“BatchUpdateException”); System.err.println(“SQLState:”+b.getSQLState()); System.err.println(“Message:”+b.getMessage()); System.err.println(“Vendor:”+b.getErrorCode()); System.err.println(“Update counts:”); int [] updateCounts=b. getUpdateCounts (); for ( int i=0; i<updateCounts.lenght; i++){ System.err.print(updateCounts[1]+” “); } }
Creating a Date Object Calendar cal=Calendar.getInstance(); cal.set(Calendar.YEAR, 2004); cal.set(Calendar.MONTH, Calendar.JANUARY); cal.set(Calendar.DATE, 24); cal.set(Calendar.HOUR, 0); cal.set(Calendar.MINUTE, 0); cal.set(Calendar.SECOND, 0); cal.set(Calendar.MILLISECOND, 0); java.sql.Date d= new java.sql.Date(cal.getTimeInMillis()); System.out.println(“Date:”+d); Date d2=Date.valueOf(“199-05-31”); Date ‘0000-00-00’ java.sql.SQLException: Value ‘0000-00-00’ can not be represented as java.sql.Date String url=”jdbc:mysql://localhost:3306/airdb?zeroDateTimeBehavior= convertToNull ”;
- Exception Throws an SQLException - Round ‘0001-01-01’ - convertToNull null Using a ResultSetMetaData Si può avere informazioni riguardo le colonne in questo oggetto ResultSet creando un oggetto ResultSetMetaData e invocando i metodi ResultSetMetaData su di esso. Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery(“SELECT * FROM aerei”); ResultSetMetaData rsmd=rs. getMetaData (); … Using the Method getColumnCount Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery(“SELECT * FROM aerei”); ResultSetMetaData rsmd=rs.getMetaData(); int numberOfColumns=rsmd. getColumnCount (); for ( int i=1; i<=numberOfColumns; i++){ String columnName=rsmd. getColumnLabel (i); System.out.print(columnName); } while (rs.next()){ for ( int i=1; i<=numberOfColumns; i++){ String columnValue=rs. getString (i); System.out.print(columnValue); }
Print a table Statement stmt=conn.createStatement(); ResultSet rs=stmt.executeQuery(“SELECT * FROM aerei”); ResultSetMetaData md=rs.getMetaData(); //print the column labels for ( int i=1; i<=md.getColumnCount(); i++) System.out.print(md.getColumnLabel(i)+” “); System.out.println(); //loop through the result set while (rs.next()){ for ( int i=1; i<=md.getColumnCount(); i++) System.out.print(rs.getString(i)+” “); System.out.println(); } rs.close(); stmt.close();