Download presentation
Presentation is loading. Please wait.
Published byJasper Horton Modified over 9 years ago
1
JDBC™ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1
2
Basic Idea Use JDBC to connect to a relational database and perform standard SQL queries to read and write data Low-level Java interface for SQL commands based on ODBC Related Concepts: –SQL –ODBC Contained in two packages –java.sql –javax.sql ©SoftMoore ConsultingSlide 2
3
JDBC Advantages Allows a pure-Java connection to a database –All programming remains in Java domain, with full access to Java features –Automatic conversion between SQL types and Java types Cross-platform and database independent –Code with any database for which there is a JDBC driver Can access virtually any data source –relational database –spreadsheet –text file ©SoftMoore ConsultingSlide 3
4
Objectives Use JDBC to connect to a relational database Execute SQL queries on the database Handle the results of a query View the structure of a database using metadata Understand JDBC exceptions and warnings ©SoftMoore ConsultingSlide 4
5
Alternatives/Related Technology Hibernate Java Data Objects (JDO) TopLink EJB3 Java Persistence API (JPA) Serialization ©SoftMoore ConsultingSlide 5
6
Using JDBC ©SoftMoore ConsultingSlide 6 JDBC/ODBC Bridge ODBC Driver Vendor- supplied JDBC Driver Database JDBC API JDBC Driver API Java Application using JDBC JDBC Driver Manager
7
JDBC Driver Types Type 1: JDBC-ODBC Bridge plus ODBC –relies on a local ODBC driver to access database –Oracle provides a JDBC-ODBC bridge –not usually suitable for production use Type 2: Native-API Partly-Java –converts JDBC calls to native database API calls of local driver –requires that some platform-specific binary code be loaded on each client machine ©SoftMoore ConsultingSlide 7
8
JDBC Driver Types (continued) Type 3: JDBC-Net Pure Java –translates JDBC calls to database-neutral protocol to communicate with a Java application server –server converts requests to connect its pure Java clients to many different databases –most flexible alternative Type 4: Native-Protocol Pure Java –converts JDBC calls directly into database-specific protocol ©SoftMoore ConsultingSlide 8
9
Vendor Support Most database vendors supply type 3 and type 4 drivers. List of companies supporting JDBC http://www.oracle.com/technetwork/java/index-136695.html List of available JDBC drivers http://www.devx.com/tips/Tip/28818 http://www.roseindia.net/tutorial/java/jdbc/listofjdbcdriver.html ©SoftMoore ConsultingSlide 9
10
ODBC Data Sources Databases accessed through ODBC are called data sources. Various kinds of ODBC data sources –relational databases –spreadsheets –text files Each ODBC data source must have an ODBC driver. The ODBC driver for the data source acts as a server to handle requests from ODBC clients. ©SoftMoore ConsultingSlide 10
11
Creating a Data Source in Windows The ODBC Data Source Dialog ©SoftMoore ConsultingSlide 11
12
SQL Conformance Databases differ on how they implement advanced SQL features. JDBC allows any string to be passed to driver, allowing access to non-standard advanced features. JDBC drivers and ODBC drivers accessed through the JDBC-ODBC bridge may have different conformance levels. ©SoftMoore ConsultingSlide 12
13
SQL Conformance: JDBC Drivers Not all JDBC drivers support latest ANSI SQL grammar. All JDBC-compliant drivers support Entry Level SQL. Use DatabaseMetaData object methods to determine conformance level: –supportsANSI92EntryLevelSQL() –supportsANSI92IntermediateSQL() –supportsANSI92FullSQL() ©SoftMoore ConsultingSlide 13
14
Using JDBC with Applets Problem: How to allow applets to access databases Issues: –Distribution (want to avoid binaries) –Security Solution: use three-tier approach: Applet ↔ server ↔ database –applet uses a socket connection to the web host to send database requests to an intermediate server –server receives the request and spawns a thread to handle the database connection –server returns the results to the applet ©SoftMoore ConsultingSlide 14
15
Basic Steps in Using JDBC Load a JDBC driver Connect to the data source Execute SQL statements Process query results Commit or rollback database changes Close the connection ©SoftMoore ConsultingSlide 15
16
The JDBC Driver Manager Management layer of JDBC When a Driver class is loaded, it registers itself with the DriverManager. The DriverManager maintains list of all drivers that have registered. Multiple drivers can be loaded/registered. The DriverManager automatically determines which driver to use for a connection. ©SoftMoore ConsultingSlide 16
17
Loading a Driver Using method Class.forName() String driverName = "oracle.jdbc.driver.OracleDriver"; Class.forName(driverName); From the property jdbc.drivers –from the command-line java -Djdbc.drivers=oracle.jdbc.driver.OracleDriver JavaProgram –from within the application System.setProperty("jdbc.drivers", "oracle.jdbc.driver.OracleDriver"); By creating an instance with a constructor –(not recommended) new oracle.jdbc.driver.OracleDriver(); ©SoftMoore ConsultingSlide 17
18
DriverManager.setLogWriter() The PrintWriter where the driver manager sends trace messages. By default, the PrintWriter used for logging is set to null (disabled). To watch log messages use PrintWriter pw = new PrintWriter(System.out); DriverManager.setLogWriter(pw); ©SoftMoore ConsultingSlide 18
19
Connecting Uses a JDBC URL of the form jdbc: : where jdbc is the protocol is the name of the driver or the database connectivity mechanism is a driver-specific name that identifies the data source (database) ©SoftMoore ConsultingSlide 19
20
Example: Making a Connection String url = "jdbc:derby:Accounts"; String user = "dba"; String pw = "Hello"; Connection conn = DriverManager.getConnection(url, user, pw); ©SoftMoore ConsultingSlide 20 Note: getConnection() throws a SQLException on failure to connect.
21
JDBC Statements Method DriverManager.getConnection() returns a Connection object. Use Connection.createStatement() to create Statement objects. Use Statement objects to execute SQL commands. Results of a query will held in ResultSet objects. ©SoftMoore ConsultingSlide 21
22
Three Kinds of JDBC Statements ©SoftMoore ConsultingSlide 22 «interface» Statement «interface» CallableStatement «interface» PreparedStatement Simple SQL statement with no parameters Precompiled SQL statement (may have input parameters) Used to execute database stored procedures
23
Statement Execute Methods JDBC statements send SQL commands by using one of three execute methods defined in the Statement interface. The method to use depends on the result of the statement: –executeQuery() is used for SELECT –executeUpdate() is used for INSERT, UPDATE, DELETE, CREATE TABLE, etc. –execute() is used rarely for very special cases ©SoftMoore ConsultingSlide 23
24
Statement.executeQuery() Used when there will be one ResultSet Represents a table of results The SQL query is passed as a String argument. ©SoftMoore ConsultingSlide 24
25
ResultSet Maintains a row cursor for iterating forward through the rows of the result table Initial position of cursor is before the first row The next() method –moves the cursor to the next row of the result table –returns true while there are more rows in the result ©SoftMoore ConsultingSlide 25
26
Example: Book Schema ©SoftMoore ConsultingSlide 26 publisher_id name url publisher book_id title isbn publisher_id book book_id author_id seq_num book_author author_id last_name first_name author
27
Executing a Query String query = "select * from book order by title"; Connection conn = DriverManager.getConnection(url, user, pw); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) {... } ©SoftMoore ConsultingSlide 27
28
GetXXX() Methods The ResultSet objects have getXXX() methods to get the values of each column in a row of data Different getXXX() method for each supported data type; e.g., getInt(), getString(),... Can refer to columns by name or number Warning: first column has number 1, not 0! ©SoftMoore ConsultingSlide 28
29
Examples: GetXXX() Methods int bookId = rs.getInt("book_id"); int bookId = rs.getInt(1); // same as above String title = rs.getString("title"); String isbn = rs.getString("isbn"); ©SoftMoore ConsultingSlide 29
30
Java-SQL Type Equivalence ©SoftMoore ConsultingSlide 30 Java MethodSQL Type boolean getBoolean()BIT short getShort()SMALLINT int getInt()INTEGER long getLong()BIGINT float getFloat()REAL double getDouble() FLOAT DOUBLE
31
Java-SQL Type Equivalence (continued) ©SoftMoore ConsultingSlide 31 Java MethodSQL Type BigDecimal getBigDecimal() NUMERIC DECIMAL String getString() CHAR VARCHAR byte[] getBytes() BINARY VARBINARY Object getObject()any type
32
Java-SQL Type Equivalence (continued) ©SoftMoore ConsultingSlide 32 Java MethodSQL Type Clob getClob()CLOB Blob getBlob()BLOB Date getDate()DATE Time getTime()TIME Timestamp getTimeStamp()TIMESTAMP Classes Blob, Clob, Date, Time, and Timestamp are defined in package java.sql.
33
Java Strings and SQL CHARS SQL types CHAR, VARCHAR, and LONGVARCHAR all map to Java strings. Fixed-length SQL strings ( CHAR(n) ) are padded to length n during conversion to Java strings. The same padding occurs when converting Java strings to SQL fixed-length strings. ©SoftMoore ConsultingSlide 33
34
Getting LONGVARCHAR as Java Streams When retrieving large strings of type LONGVARCHAR, the ResultSet methods –getAsciiStream() and –getUnicodeStream() can be used to get the value as a stream. ©SoftMoore ConsultingSlide 34
35
Binary SQL Values As with SQL strings, SQL binary types, BINARY, VARBINARY, and LONGVARBINARY are all mapped to Java byte[] objects The ResultSet method getBinaryStream() can be used to read large binary objects ( LONGVARBINARY ) ©SoftMoore ConsultingSlide 35
36
Example: List Books by James Rumbaugh String query = "select b.title" + " from book b, book_author ba, author a" + " where b.book_id = ba.book_id" + " and ba.author_id = a.author_id" + " and a.first_name = 'James'" + " and a.last_name = 'Rumbaugh'" + " order by title"; ConnectionFactory factory = ConnectionFactory.getInstance(); Connection conn = factory.getConnection(); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery(query); System.out.println("Books by James Rumbaugh"); while (rs.next()) System.out.println("- " + rs.getString("title")); ©SoftMoore ConsultingSlide 36
37
Statement.executeUpdate() Used for INSERT, UPDATE, or DELETE statements Also used for SQL data definition statements like CREATE TABLE and ALTER TABLE Return value is number of rows modified (there is no ResultSet object) ©SoftMoore ConsultingSlide 37
38
Example: Inserting Data static String[] sqlInserts = { "insert into author values (1000, 'Gamma', 'Erich')", "insert into author values (1001, 'Helm', 'Richard')", "insert into author values (1002, 'Johnson', 'Ralph')",... } int updateCount = 0; for (int i = 0; i < sqlInserts.length; ++i) updateCount += stmt.executeUpdate(sqlInserts[i]); ©SoftMoore ConsultingSlide 38
39
Additional Update Examples // create table with name and height columns stmt.executeUpdate("create table Data " + "(name varchar(30), height integer)"); // inserting data stmt.executeUpdate("insert into Data " + "values ('John', 68)"); // updating data stmt.executeUpdate("update Data" + " set height = 70" + " where name = 'John'"); // deleting data stmt.executeUpdate("delete from Data" + " where name = 'John'"); ©SoftMoore ConsultingSlide 39
40
Statement.execute() Used for cases when the statement might –return more than one ResultSet –return more than one update count (number of rows modified) –return a combination of both Can always be used if programmer is unsure of the result Example: A stored procedure may execute multiple statements, each of which will have a result. ©SoftMoore ConsultingSlide 40
41
Retrieving Results From Statement.execute() Method Statement.execute() returns a boolean –true if next result is a ResultSet –false if next result is an update count –false if there are no more results Use Statement.getResultSet() to get the current result as a ResultSet object Use Statement.getMoreResults() to move to the next result Use Statement.getUpdateCount() to get the current result as an update count ©SoftMoore ConsultingSlide 41
42
Multiple Result Sets In Practice Not common Used primarily when the programmer usually knows what to expect, either from database or stored procedure documentation Might not be supported by the database. ©SoftMoore ConsultingSlide 42
43
Closing the Connection Ensures that system resources are freed conn.close(); Can also close –Statement objects closed automatically when the connection is closed –ResultSet objects closed automatically when the statement is closed ©SoftMoore ConsultingSlide 43
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.