The Codex of Business Writing Software for Real-World Solutions 2.pptx
Basi Dati F2
1. Download JDBC Goals
` Download PostgresSQL ` SQL Level
` http://www.postgresql.org/download/ ` 100% Pure Java
` Keep it simple
` Download jdbc driver for PostgresSQL ` High performance
` http://jdbc.postgresql.org/download.html ` Leverage existing database technology
` why reinvent the wheel?
Basi di Dati ` Create database ` Use strong, static typing wherever possible
` Esami ` Use multiple methods to express multiple functionality
` Create
jdbc
` User ‘user’, Password ‘pw’
3 jdbc 4 jdbc
JDBC Architecture java.sql DriverManager
` Java code calls JDBC library ` JDBC is implemented via classes in the java.sql package ` DriverManager tries all the drivers
` JDBC loads a driver ` Uses the first one that works
` Driver talks to a particular database ` When a driver class is first loaded, it registers itself with
the DriverManager
` Can have more than one driver > more than one
` Therefore, to register a driver, just load it!
database
` Ideal: can change database engines without changing
any application code
Application JDBC Driver
5 jdbc 6 jdbc 7 jdbc
2. Registering a Driver JDBC Object Classes JDBC Class Usage
` Statically load driver ` DriverManager
` Loads, chooses drivers DriverManager
Class.forName(“org.postgresql.Driver”); ` Driver
Connection c = ` connects to actual database Driver
DriverManager.getConnection(...); ` Connection
` a series of SQL statements to and from the DB Connection
` Statement/PreparedStatement
Statement
` a single SQL statement
` ResultSet PreparedStatement
` the records returned from a Statement/PreparedStatement
ResultSet
8 jdbc 9 jdbc 10 jdbc
JDBC URLs DriverManager Connection
jdbc:subprotocol:source Connection getConnection ` A Connection represents a session with a specific database.
(String url, String user, String password)
` Within the context of a Connection, SQL statements are
` each driver has its own subprotocol executed and results are returned.
` each subprotocol has its own syntax for the source ` Connects to given JDBC URL with given user name and
password ` Can have multiple connections to a database
` NB: Some drivers don’t support serialized connections
jdbc:odbc:DataSource ` Throws java.sql.SQLException ` Fortunately, most do (now)
` e.g. jdbc:odbc:Northwind ` Returns a Connection object
jdbc:mysql://host[:port]/database ` Also provides “metadata” information about the database,
tables, and fields
` e.g. jdbc:msql://foo.nowhere.com:4333/accounting
jdbc:postgresql://host:port/database ` Also methods to deal with transactions
` e.g. jdbc:postgresql://localhost:5432/esami
11 jdbc 12 jdbc 13 jdbc
3. Obtaining a Connection Connection Methods Statement
try{ Statement createStatement() ` A Statement object is used for executing a static SQL
Class.forName (quot;org.postgresql.Driverquot;); // Load the Driver
` returns a new Statement object
Connection conn = DriverManager.getConnection
statement and obtaining the results produced by it.
(quot;jdbc:postgresql://localhost:5432/esamiquot;, quot;userquot;, quot;pwquot; );
Statement stmt = conn.createStatement(); PreparedStatement prepareStatement(String sql)
//... ` returns a new PreparedStatement object
stmt.close();
conn.close();
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
14 jdbc 15 jdbc 16 jdbc
Statement Methods Statement Methods ResultSet
ResultSet executeQuery(String) ... ` A ResultSet provides access to a table of data generated
` Execute a SQL statement that returns a single ResultSet.
String sql = by executing a Statement.
quot;CREATE TABLE STUDENTI
(matr integer primary key, cognome varchar, nome varchar)quot;;
stmt.executeUpdate(sql);
` Only one ResultSet per Statement can be open at once.
int executeUpdate(String)
` Execute a SQL INSERT, UPDATE or DELETE statement. sql = ` The table rows are retrieved in sequence.
Returns the number of rows changed. quot;INSERT INTO STUDENTI VALUES(1, 'rossi', 'mario'),
(2, 'bianchi', 'sergio')quot;;
` A ResultSet maintains a cursor pointing to its current row
stmt.executeUpdate(sql);
boolean execute(String) of data.
sql =
` Execute a SQL statement that may return multiple results.
quot;SELECT * FROM STUDENTIquot;; ` The 'next' method moves the cursor to the next row.
ResultSet rs = stmt.executeQuery(sql); ` you can’t rewind
...
17 jdbc 18 jdbc 19 jdbc
4. ResultSet Methods ResultSet Methods ResultSet Methods
` boolean next() ` Type getType(int columnIndex) ` String getString(int columnIndex)
` activates the next row ` returns the given field as the given type ` boolean getBoolean(int columnIndex)
` the first call to next() activates the first row ` fields indexed starting at 1 (not 0) ` byte getByte(int columnIndex)
` returns false if there are no more rows ` short getShort(int columnIndex)
` Type getType(String columnName)
` int getInt(int columnIndex)
` void close() ` same, but uses name of field
` long getLong(int columnIndex)
` disposes of the ResultSet ` less efficient
` float getFloat(int columnIndex)
` allows you to re use the Statement that created it ` int findColumn(String columnName)
` double getDouble(int columnIndex)
` automatically called by most Statement methods ` looks up column index given column name
` Date getDate(int columnIndex)
` Time getTime(int columnIndex)
` Timestamp getTimestamp(int columnIndex)
20 jdbc 21 jdbc 22 jdbc
ResultSet Methods ResultSet Methods Mapping Java Types to SQL Types
...
` String getString(String columnName)
sql = quot;SELECT * FROM STUDENTIquot;;
` boolean getBoolean(String columnName) SQL type Java Type
ResultSet rs = stmt.executeQuery(sql);
` byte getByte(String columnName) CHAR, VARCHAR, LONGVARCHAR String
NUMERIC, DECIMAL java.math.BigDecimal
` short getShort(String columnName) while (rs.next()) { BIT boolean
int matr = rs.getInt(quot;matrquot;); TINYINT byte
` int getInt(String columnName)
String cognome = rs.getString(quot;cognomequot;); SMALLINT short
` long getLong(String columnName) INTEGER int
String nome = rs.getString(quot;nomequot;);
` float getFloat(String columnName) System.out.println(matr+quot; quot;+cognome+quot; quot;+nome); BIGINT long
REAL float
` double getDouble(String columnName) }
FLOAT, DOUBLE double
rs.close();
` Date getDate(String columnName) BINARY, VARBINARY, LONGVARBINARY byte[]
stmt.close(); DATE java.sql.Date
` Time getTime(String columnName) ... TIME java.sql.Time
` Timestamp getTimestamp(String columnName) TIMESTAMP java.sql.Timestamp
23 jdbc 24 jdbc 25 jdbc
5. PreparedStatement motivation PreparedStatement PreparedStatement
...
` Suppose we would like to run the query ` PreparedStatement prepareStatement(String) sql = quot;SELECT * FROM STUDENTI WHERE nome = ? and matr > ?quot;;
` returns a new PreparedStatement object PreparedStatement preparedStatement = conn.prepareStatement(sql);
SELECT * FROM STUDENTI preparedStatement.setString(1, quot;sergioquot;);
preparedStatement.setInt(2, 0);
WHERE name=‘sergio’; ` Prepared Statements are used for queries that are rs = preparedStatement.executeQuery();
while (rs.next()) {
executed many times with possibly different contents. int matr = rs.getInt(1);
String cognome = rs.getString(2);
` A PreparedStatement object includes the query and is
` But we would like to run this for all students String nome = rs.getString(3);
prepared for execution (precompiled). System.out.println(matr+quot; quot;+cognome+quot; quot;+nome);
(separately), not only ‘sergio’… ` Question marks can be inserted as variables. }
rs.close();
` Could we create a variable instead of ‘sergio’ which ` setString(i, value) The i th question mark is set preparedStatement.close();
conn.close();
would get a different name every time??.. ` setInt(i, value) to the given value. }
...
26 jdbc 27 jdbc 28 jdbc
PreparedStatement JDBC Class Diagram
` Will this work?
PreparedStatement pstmt =
con.prepareStatement(“select * from ?”);
pstmt.setString(1, quot;Sailorsquot;);
` No! We may put ? only instead of values
29 jdbc 30 jdbc