JDBCâ„¢ Fundamentals (a.k.a. Java Database Connectivity, although technically not...

download JDBCâ„¢ Fundamentals (a.k.a. Java Database Connectivity, although technically not an acronym) ©SoftMoore ConsultingSlide 1

of 43

  • date post

    21-Jan-2016
  • Category

    Documents

  • view

    217
  • download

    0

Embed Size (px)

Transcript of JDBCâ„¢ Fundamentals (a.k.a. Java Database Connectivity, although technically not...

JDBC

JDBC Fundamentals(a.k.a. Java Database Connectivity,although technically not an acronym)SoftMoore ConsultingSlide 1JDBC Fundamentals1Basic IdeaUse JDBC to connect to a relational database and perform standard SQL queries to read and write dataLow-level Java interface for SQL commands based on ODBCRelated Concepts:SQLODBCContained in two packagesjava.sqljavax.sqlSoftMoore ConsultingSlide 2JDBC Fundamentals2JDBC AdvantagesAllows a pure-Java connection to a databaseAll programming remains in Java domain, with full access to Java featuresAutomatic conversion between SQL types and Java typesCross-platform and database independentCode with any database for which there is a JDBC driverCan access virtually any data sourcerelational databasespreadsheettext file

SoftMoore ConsultingSlide 3JDBC Fundamentals3ObjectivesUse 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 metadataUnderstand JDBC exceptions and warnings

SoftMoore ConsultingSlide 4JDBC Fundamentals4Alternatives/Related TechnologyHibernateJava Data Objects (JDO)TopLinkEJB3 Java Persistence API (JPA)SerializationSoftMoore ConsultingSlide 5JDBC Fundamentals5Using JDBCSoftMoore ConsultingSlide 6JDBC/ODBCBridgeODBCDriverVendor-suppliedJDBC DriverDatabaseDatabaseJDBC APIJDBC Driver APIJava Applicationusing JDBCJDBC Driver ManagerJDBC Fundamentals6JDBC Driver TypesType 1: JDBC-ODBC Bridge plus ODBCrelies on a local ODBC driver to access database Oracle provides a JDBC-ODBC bridge not usually suitable for production useType 2: Native-API Partly-Javaconverts JDBC calls to native database API calls of local driverrequires that some platform-specific binary code be loaded on each client machineSoftMoore ConsultingSlide 7JDBC Fundamentals7JDBC Driver Types(continued)Type 3: JDBC-Net Pure Javatranslates JDBC calls to database-neutral protocol to communicate with a Java application serverserver converts requests to connect its pure Java clients to many different databasesmost flexible alternativeType 4: Native-Protocol Pure Javaconverts JDBC calls directly into database-specific protocolSoftMoore ConsultingSlide 8JDBC Fundamentals8Vendor SupportMost database vendors supply type 3 and type 4 drivers.List of companies supporting JDBChttp://www.oracle.com/technetwork/java/index-136695.html List of available JDBC drivershttp://www.devx.com/tips/Tip/28818http://www.roseindia.net/tutorial/java/jdbc/listofjdbcdriver.html SoftMoore ConsultingSlide 9JDBC Fundamentals9ODBC Data SourcesDatabases accessed through ODBC are called data sources.Various kinds of ODBC data sources relational databasesspreadsheets text filesEach 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 10JDBC Fundamentals10Creating a Data Source in WindowsThe ODBC Data Source DialogSoftMoore ConsultingSlide 11

JDBC Fundamentals11SQL ConformanceDatabases 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 12JDBC Fundamentals12SQL Conformance: JDBC DriversNot 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 13JDBC Fundamentals13Using JDBC with AppletsProblem: How to allow applets to access databases Issues: Distribution (want to avoid binaries) Security Solution: use three-tier approach: Applet server databaseapplet 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 14JDBC Fundamentals14Basic Steps in Using JDBCLoad a JDBC driverConnect to the data sourceExecute SQL statementsProcess query resultsCommit or rollback database changesClose the connectionSoftMoore ConsultingSlide 15JDBC Fundamentals15The JDBC Driver ManagerManagement layer of JDBCWhen 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 driverto use for a connection.SoftMoore ConsultingSlide 16JDBC Fundamentals16Loading a DriverUsing method Class.forName()String driverName = "oracle.jdbc.driver.OracleDriver";Class.forName(driverName);From the property jdbc.driversfrom the command-linejava -Djdbc.drivers=oracle.jdbc.driver.OracleDriver JavaProgramfrom within the applicationSystem.setProperty("jdbc.drivers", "oracle.jdbc.driver.OracleDriver");By creating an instance with a constructor(not recommended)new oracle.jdbc.driver.OracleDriver();SoftMoore ConsultingSlide 17JDBC Fundamentals17DriverManager.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 18JDBC Fundamentals18ConnectingUses a JDBC URL of the form jdbc::wherejdbc 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 19JDBC Fundamentals19Example: Making a ConnectionString url = "jdbc:derby:Accounts";String user = "dba";String pw = "Hello";

Connection conn = DriverManager.getConnection(url, user, pw);

SoftMoore ConsultingSlide 20Note: getConnection() throws aSQLException on failure to connect.JDBC Fundamentals20JDBC StatementsMethod 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 21JDBC Fundamentals21Three Kinds of JDBC StatementsSoftMoore ConsultingSlide 22interfaceStatementinterfaceCallableStatementinterfacePreparedStatementSimple SQL statement with no parametersPrecompiled SQL statement (may have input parameters)Used to execute database stored proceduresJDBC Fundamentals22Statement Execute MethodsJDBC 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 SELECTexecuteUpdate() is used for INSERT, UPDATE, DELETE, CREATE TABLE, etc.execute() is used rarely for very special casesSoftMoore ConsultingSlide 23JDBC Fundamentals23Statement.executeQuery()Used when there will be one ResultSetRepresents a table of results The SQL query is passed as a String argument.SoftMoore ConsultingSlide 24JDBC Fundamentals24ResultSetMaintains a row cursor for iterating forward through the rows of the result tableInitial position of cursor is before the first rowThe next() methodmoves the cursor to the next row of the result tablereturns true while there are more rows in the resultSoftMoore ConsultingSlide 25JDBC Fundamentals25Example: Book SchemaSoftMoore ConsultingSlide 26publisher_id name urlpublisherbook_id title isbn publisher_idbookbook_id author_id seq_numbook_authorauthor_id last_name first_nameauthorJDBC Fundamentals26Executing a QueryString 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 27JDBC Fundamentals27GetXXX() MethodsThe ResultSet objects have getXXX() methods to get the values of each column in a row of dataDifferent 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 28JDBC Fundamentals28Examples: GetXXX() Methodsint 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 29JDBC Fundamentals29Java-SQL Type EquivalenceSoftMoore ConsultingSlide 30Java MethodSQL Typeboolean getBoolean()BITshort getShort()SMALLINTint getInt()INTEGERlong getLong()BIGINTfloat getFloat()REALdouble getDouble()FLOATDOUBLEJDBC Advanced Concepts30Java-SQL Type Equivalence(continued)SoftMoore ConsultingSlide 31Java MethodSQL TypeBigDecimal getBigDecimal()NUMERICDECIMALString getString()CHARVARCHARbyte[] getBytes()BINARYVARBINARYObject getObject()any typeJDBC Advanced Concepts31Java-SQL Type Equivalence(continued)SoftMoore ConsultingSlide 32Java MethodSQL TypeClob getClob()CLOBBlob getBlob()BLOBDate getDate()DATETime getTime()TIMETimestamp getTimeStamp()TIMESTAMPClasses Blob, Clob, Date, Time, and Timestampare defined in package java.sql.JDBC Advanced Concepts32Java Strings and SQL CHARSSQL 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 33JDBC Advanced Concepts33Getting LONGVARCHAR as Java StreamsWhen retrieving large strings of type LONGVARCHAR, the ResultSet methodsgetAsciiStream() andgetUnicodeStream()can be used to get the value as a stream.SoftMoore ConsultingSlide 34JDBC Advanced Concepts34Binary SQL ValuesAs with SQL strings, SQL bi