Download presentation
Presentation is loading. Please wait.
Published byErnest Allison Modified over 9 years ago
1
JDBC and Database Programming in Java
2
Introduction u Database Access in Java u Find out any relevant background and interest of the audience u SQL gurus? u Visual Basic Database Forms?
3
Agenda u Overview of Databases and Java u Overview of JDBC u JDBC APIs u Other Database Techniques
4
Overview TCP/IP java.net RMI JDBC CORBA Network OS around 4pm
5
Part I: Overview of Databases and Java
6
Databases in the Enterprise u All corporate data stored in DB u SQL standardizes format (sort of)
7
Why Java? u Write once, run anywhere u Multiple client and server platforms u Object-relational mapping u databases optimized for searching/indexing u objects optimized for engineering/flexibility u Network independence u Works across Internet Protocol u Database independence u Java can access any database vendor u Ease of administration u zero-install client
8
Database Architectures u Two-tier u Three-tier u N-tier
9
Two-Tier Architecture u Client connects directly to server u e.g. HTTP, email u Pro: u simple u client-side scripting offloads work onto the client u Con: u fat client u inflexible
10
Three-Tier Architecture u Application Server sits between client and database
11
Three-Tier Pros u flexible: can change one part without affecting others u can connect to different databases without changing code u specialization: presentation / business logic / data management u can cache queries u can implement proxies and firewalls
12
Three-Tier Cons u higher complexity u higher maintenance u lower network efficiency u more parts to configure (and buy)
13
N-Tier Architecture u Design your application using as many “tiers” as you need u Use Object-Oriented Design techniques u Put the various components on whatever host makes sense u Java allows N-Tier Architecture, especially with RMI and JDBC
14
Database Technologies u Hierarchical u obsolete (in a manner of speaking) u any specialized file format can be called a hierarchical DB u Relational (aka SQL) (RDBMS) u row, column u most popular u Object-relational DB (ORDBMS) u add inheritance, blobs to RDB u NOT object-oriented -- “object” is mostly a marketing term u Object-oriented DB (OODB) u data stored as objects u high-performance for OO data models
15
Relational Databases u invented by Dr. E.F.Codd u data stored in records which live in tables u maps row (record) to column (field) in a single table u “relation” (as in “relational”) means row to column (not table to table)
16
Joining Tables u you can associate tables with one another u allows data to nest u allows arbitrarily complicated data structures u not object-oriented
17
Join example u People u name u homeaddress u workaddress u Addresses u id u street u state u zip
18
SQL u Structured Query Language u Standardized syntax for “querying” (accessing) a relational database u Supposedly database-independent u Actually, there are important variations from DB to DB
19
SQL Syntax INSERT INTO table ( field1, field2 ) VALUES ( value1, value2 ) u inserts a new record into the named table UPDATE table SET ( field1 = value1, field2 = value2 ) WHERE condition u changes an existing record or records DELETE FROM table WHERE condition u removes all records that match condition SELECT field1, field2 FROM table WHERE condition u retrieves all records that match condition
20
Transactions u Transaction = more than one statement which must all succeed (or all fail) together u If one fails, the system must reverse all previous actions u Also can’t leave DB in inconsistent state halfway through a transaction u COMMIT = complete transaction u ROLLBACK = abort
21
Part II: JDBC Overview
22
JDBC Goals u SQL-Level u 100% Pure Java u Keep it simple u High-performance u Leverage existing database technology u why reinvent the wheel? u Use strong, static typing wherever possible u Use multiple methods to express multiple functionality
23
JDBC Ancestry X/OPEN ODBC JDBC
24
JDBC Architecture ApplicationJDBCDriver u Java code calls JDBC library u JDBC loads a driver u Driver talks to a particular database u Can have more than one driver -> more than one database u Ideal: can change database engines without changing any application code
25
JDBC Drivers u Type I: “Bridge” u Type II: “Native” u Type III: “Middleware” u Type IV: “Pure”
26
JDBC Drivers (Fig.) JDBC Type I “Bridge” Type II “Native” Type III “Middleware” Type IV “Pure” ODBC Driver CLI (.lib) Middleware Server
27
Type I Drivers u Use bridging technology u Requires installation/configuration on client machines u Not good for Web u e.g. ODBC Bridge
28
Type II Drivers u Native API drivers u Requires installation/configuration on client machines u Used to leverage existing CLI libraries u Usually not thread-safe u Mostly obsolete now u e.g. Intersolv Oracle Driver, WebLogic drivers
29
Type III Drivers u Calls middleware server, usually on database host u Very flexible -- allows access to multiple databases using one driver u Only need to download one driver u But it’s another server application to install and maintain u e.g. Symantec DBAnywhere
30
Type IV Drivers u 100% Pure Java -- the Holy Grail u Use Java networking libraries to talk directly to database engines u Only disadvantage: need to download a new driver for each database engine u e.g. Oracle, mSQL
31
JDBC Limitations u No scrolling cursors u No bookmarks
32
Related Technologies u ODBC u Requires configuration (odbc.ini) u RDO, ADO u Requires Win32 u OODB u e.g. ObjectStore from ODI u JavaBlend u maps objects to tables transparently (more or less)
33
Part III: JDBC APIs
34
java.sql u JDBC is implemented via classes in the java.sql package
35
Loading a Driver Directly Driver d = new foo.bar.MyDriver(); Connection c = d.connect(...); u Not recommended, use DriverManager instead u Useful if you know you want a particular driver
36
DriverManager u DriverManager tries all the drivers u Uses the first one that works u When a driver class is first loaded, it registers itself with the DriverManager u Therefore, to register a driver, just load it!
37
Registering a Driver u statically load driver Class.forName(“foo.bar.MyDriver”); Connection c = DriverManager.getConnection(...); or use the jdbc.drivers system property
38
JDBC Object Classes u DriverManager u Loads, chooses drivers u Driver u connects to actual database u Connection u a series of SQL statements to and from the DB u Statement u a single SQL statement u ResultSet u the records returned from a Statement
39
JDBC Class Usage DriverManager Driver Connection Statement ResultSet
40
JDBC URLs jdbc:subprotocol:source u each driver has its own subprotocol u each subprotocol has its own syntax for the source jdbc:odbc:DataSource e.g. jdbc:odbc:Northwind jdbc:msql://host[:port]/database e.g. jdbc:msql://foo.nowhere.com:4333/accounting
41
DriverManager Connection getConnection (String url, String user, String password) u Connects to given JDBC URL with given user name and password u Throws java.sql.SQLException u returns a Connection object
42
Connection u A Connection represents a session with a specific database. u Within the context of a Connection, SQL statements are executed and results are returned. u Can have multiple connections to a database u NB: Some drivers don’t support serialized connections u Fortunately, most do (now) u Also provides “metadata” -- information about the database, tables, and fields u Also methods to deal with transactions
43
Obtaining a Connection String url = "jdbc:odbc:Northwind"; try { Class.forName ("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection(url); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }
44
Connection Methods Statement createStatement() u returns a new Statement object PreparedStatement prepareStatement(String sql) u returns a new PreparedStatement object CallableStatement prepareCall(String sql) u returns a new CallableStatement object u Why all these different kinds of statements? Optimization.
45
Statement u A Statement object is used for executing a static SQL statement and obtaining the results produced by it.
46
Statement Methods ResultSet executeQuery(String) u Execute a SQL statement that returns a single ResultSet. int executeUpdate(String) u Execute a SQL INSERT, UPDATE or DELETE statement. Returns the number of rows changed. boolean execute(String) u Execute a SQL statement that may return multiple results. u Why all these different kinds of queries? Optimization.
47
ResultSet u A ResultSet provides access to a table of data generated by executing a Statement. u Only one ResultSet per Statement can be open at once. u The table rows are retrieved in sequence. u A ResultSet maintains a cursor pointing to its current row of data. u The 'next' method moves the cursor to the next row. u you can’t rewind
48
ResultSet Methods u boolean next() u activates the next row u the first call to next() activates the first row u returns false if there are no more rows u void close() u disposes of the ResultSet u allows you to re-use the Statement that created it u automatically called by most Statement methods
49
ResultSet Methods u Type getType(int columnIndex) u returns the given field as the given type u fields indexed starting at 1 (not 0) u Type getType(String columnName) u same, but uses name of field u less efficient u int findColumn(String columnName) u looks up column index given column name
50
ResultSet Methods u String getString(int columnIndex) u boolean getBoolean(int columnIndex) u byte getByte(int columnIndex) u short getShort(int columnIndex) u int getInt(int columnIndex) u long getLong(int columnIndex) u float getFloat(int columnIndex) u double getDouble(int columnIndex) u Date getDate(int columnIndex) u Time getTime(int columnIndex) u Timestamp getTimestamp(int columnIndex)
51
ResultSet Methods u String getString(String columnName) u boolean getBoolean(String columnName) u byte getByte(String columnName) u short getShort(String columnName) u int getInt(String columnName) u long getLong(String columnName) u float getFloat(String columnName) u double getDouble(String columnName) u Date getDate(String columnName) u Time getTime(String columnName) u Timestamp getTimestamp(String columnName)
52
isNull u In SQL, NULL means the field is empty u Not the same as 0 or “” u In JDBC, you must explicitly ask if a field is null by calling ResultSet.isNull(column)
53
Sample Database Employee IDLast NameFirst Name 1DavolioNancy 2FullerAndrew 3LeverlingJanet 4PeacockMargaret 5BuchananSteven
54
SELECT Example Connection con = DriverManager.getConnection(url, "alex", "8675309"); Statement st = con.createStatement(); ResultSet results = st.executeQuery("SELECT EmployeeID, LastName, FirstName FROM Employees");
55
SELECT Example (Cont.) while (results.next()) { int id = results.getInt(1); String last = results.getString(2); String first = results.getString(3); System.out.println("" + id + ": " + first + " " + last); } st.close(); con.close();
56
Mapping Java Types to SQL Types SQL type Java Type CHAR, VARCHAR, LONGVARCHARString NUMERIC, DECIMALjava.math.BigDecimal BITboolean TINYINTbyte SMALLINTshort INTEGERint BIGINTlong REALfloat FLOAT, DOUBLEdouble BINARY, VARBINARY, LONGVARBINARYbyte[] DATEjava.sql.Date TIMEjava.sql.Time TIMESTAMPjava.sql.Timestamp
57
Database Time u Times in SQL are notoriously unstandard u Java defines three classes to help u java.sql.Date u year, month, day u java.sql.Time u hours, minutes, seconds u java.sql.Timestamp u year, month, day, hours, minutes, seconds, nanoseconds u usually use this one
58
Modifying the Database u use executeUpdate if the SQL contains “INSERT” or “UPDATE” u Why isn’t it smart enough to parse the SQL? Optimization. u executeUpdate returns the number of rows modified u executeUpdate also used for “CREATE TABLE” etc. (DDL)
59
INSERT example
60
Transaction Management u Transactions are not explicitly opened and closed u Instead, the connection has a state called AutoCommit mode u if AutoCommit is true, then every statement is automatically committed u default case: true
61
setAutoCommit Connection.setAutoCommit(boolean) u if AutoCommit is false, then every statement is added to an ongoing transaction u you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback()
62
Connection Managers u Hint: for a large threaded database server, create a Connection Manager object u It is responsible for maintaining a certain number of open connections to the database u When your applications need a connection, they ask for one from the CM’s pool u Why? Because opening and closing connections takes a long time u Warning: the CM should always setAutoCommit(false) when a connection is returned
63
Optimized Statements u Prepared Statements u SQL calls you make again and again u allows driver to optimize (compile) queries u created with Connection.prepareStatement() u Stored Procedures u written in DB-specific language u stored inside database u accesed with Connection.prepareCall()
64
JDBC Class Diagram Whoa!
65
Metadata u Connection: u DatabaseMetaData getMetaData() u ResultSet: u ResultSetMetaData getMetaData()
66
ResultSetMetaData u What's the number of columns in the ResultSet? u What's a column's name? u What's a column's SQL type? u What's the column's normal max width in chars? u What's the suggested column title for use in printouts and displays? u What's a column's number of decimal digits? u Does a column's case matter? u Is the column a cash value? u Will a write on the column definitely succeed? u Can you put a NULL in this column? u Is a column definitely not writable? u Can the column be used in a where clause? u Is the column a signed number? u Is it possible for a write on the column to succeed? u and so on...
67
DatabaseMetaData u What tables are available? u What's our user name as known to the database? u Is the database in read-only mode? u If table correlation names are supported, are they restricted to be different from the names of the tables? u and so on…
68
JavaBlend: Java to Relational Mapping
69
JDBC 2.0 u Scrollable result set u Batch updates u Advanced data types u Blobs, objects, structured types u Rowsets u Persistent JavaBeans u JNDI u Connection Pooling u Distributed transactions via JTS
70
Where to get more information u Other training sessions u Reese, Database Programming with JDBC and Java (O’Reilly) u http://java.sun.com/products/jdbc/ u http://java.sun.com/products/java-blend/ u http://www.purpletech.com/java/
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.