JDBC
Framing Accessing DBMS from your code A possible way of writing applications accessing DBMS You ll see other ways via Web technologies ODBC: Open Data Base Connectivity C/C++ API JDBC: Java Data Base Connectivity Java API Both define interfaces, i.e. Set of methods you can use to do SQL queries (both DDL and DML) 2
JDBC Architecture 3
Advantages Separate your code from the native language of the DBMS You can use JDBC with any DBMS that provides a driver (or for which a bridge is available, see later) Not necessarily a relational DBMS But JDBC always accepts SQL-like statements! You can re-use your code with any DBMS Provided you have the relative driver 4
Lab setup PostgreSQL provides native Java drivers Postgresql JDBC library must be included in NetBeans projects project s properties libraries run and/or compile add postgresql JDBC driver 8
Typical actions within the code Load the DBMS driver Create a Connection with the DBMS Any number of times Submit SQL statements Retrieve results Process data/errors Commit or rollback Close the connection 9
Code spots Using (at least) one java package to interact with the JDBC driver import java.sql.*; in your import list javax.sql: advanced feature (we will not cover them) Load the driver Class.forName( org.postgresql.driver ); Catch a ClassNotFound exception!!! Connect to the DBMS String url= jdbc:postrgesql://delmastrof.iit.cnr.it/u01db ; Connection con = DriverManager.getConnection(url, u01, m-s-t+20+12 ); user password 10
(A bit more) General format of the URL string Connect to the DBMS String url= jdbc:postrgesql://delmastrof.iit.cnr.it/u01db ; Connection con = DriverManager.getConnection(url, u01, m-s-t+20+12 ); 11
Submit SQL statements DML Statement st = con.createstatement(); ResultSet rs = st.executequery( SELECT * FROM net WHERE gw= 192.168.2.1 ); Or, you can use PreparedStatements: DDL PreparedStatement pst = con.preparestatement( S E L E C T * F R O M n e t W H E R E a d m i n =? ) ; pst.clearparameters(); pst.setstring(1, gianni ); ResultSet rs = pst.executequery(); Statement st = con.createstatement( INSERT INTO net VALUES ( andrea, 192.168.5.1, 192.168.5.0/24 ) ); int numrows = st.executeupdate(); 12
Getting results back DDL statements return the number of rows modified Statement st = con.createstatement( INSERT INTO net VALUES ( andrea, 192.168.5.1, 192.168.5.0/24 ) ); int numrows = st.executeupdate(); DML statements return a ResultSet (an iterator) ResultSet rs = st.executequery(query); while(rs.next()){ String ad = rs.getstring( admin ); // or, String ad = rs.getstring(1); if admin is the first // field of the table } Move in the ResultSet with methods previous(), absolute(int), relative(int), first(), last() 13
ResultSet and Statements A ResultSet is associated with the previous statement Don t issue another query via the same statement before getting back all results: WRONG ResultSet rs = st.executequery(query); while(rs.next()){ S t r i n g a d = r s. g e t S t r i n g ( a d m i n ) ; ResultSet rs1 = st.executequery(query1); } CORRECT ResultSet rs = st.executequery(query); Statement st1 = con.createstatement(); while(rs.next()){ S t r i n g a d = r s. g e t S t r i n g ( a d m i n ) ; ResultSet rs1 = st1.executequery(query1); } 14
Data types Most are already defined by Java integer, String, Other are defined in the java.sql package java.sql.date, java.sql.time, java.sql.timestamp, Other within the driver package Org.postgresql.geometric.PGcircle, Org.postgresql.geometric.PGline, See http://jdbc.postgresql.org/documentation/publicapi/ index.html 15
Transactions By default, each statement is a transaction To alter this, Connection con = ; con.setautocommit(false); // con.getautocommit() to retrieve the current commit mode con.commit(); to close a transaction explicitly 16
Exceptions Methods throw SQLException getsqlstate() return a SQL state identifier geterrorcode() return a vendor-specific error code So, typically try{ Statement st = con.createstatement(); ResultSet rs = st.executequery(query); while(rs.next()){ // process results } } catch SQLException(e){ // process exception here } 17
Getting metadata Use ResultSetMetaData type to get metadata about a ResultSet Information such as the name and type of fields Have a look at host.java In general, use the Java API specs for documentation http://java.sun.com/j2se/1.4.2/docs/api/index.html 18
Secure connections String url = jdbc:postrgesql://delmastrof.iit.cnr.it/u01db? user=u01&password=m-s-t+20+12&ssl=true ; Connection con = DriverManager.getConnection(url); 19
Secure connections String url = jdbc:postrgesql://delmastrof.iit.cnr.it/u01db? user=u01&password=m-s-t+20+12&ssl=true& sslfactory=org.postgresql.ssl.nonvalidatingfactory ; Connection con = DriverManager.getConnection(url); String url = "jdbc:postgresql://delmastrof.iit.cnr.it/u01db ; Properties props = new Properties(); props.setproperty("user", u01"); props.setproperty("password", m-s-t+20+12"); props.setproperty("ssl","true"); props.setproperty("sslfactory", "org.postgresql.ssl.nonvalidatingfactory"); // no cert. validation Connection conn = DriverManager.getConnection(url, props); See http://jdbc.postgresql.org/documentation/84/connect.html http://jdbc.postgresql.org/documentation/84/ssl-client.html 20
Useful examples provafile.java Managing I/O from/to file provaio.java Managing input from keyboard provainet.java Managing network data types 21
NetBeans working directory header of any relative path in your source code 22