Copyright © 1997 Alex Chaffee JDBC and Database Programming in Java Alexander Day Chaffee Version 1.1, 14 Feb 98.

Slides:



Advertisements
Similar presentations
Connecting to Databases. relational databases tables and relations accessed using SQL database -specific functionality –transaction processing commit.
Advertisements

Basic JDBC Celsina Bignoli What is JDBC Industry standard for database- connectivity between the Java language and a wide range of.
JDBC - Java Database Connectivity The objectives of this chapter are: To describe the architecture of JDBC To outline the classes in the java.sql package.
1 JDBC Java Database Connectivity. 2 c.pdf
1 JDBC: Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
מסדי נתונים תשס " ג 1 JDBC Java Database Connectivity קורס מסדי נתונים.
1 C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California
1 JDBC – Java Database Connectivity Representation and Management of Data on the Internet.
1 Oracle Database Applications Database Connectivity.
UFCE4Y UFCE4Y-20-3 Components and Services Julia Dawson.
JDBC / ODBC JDBC is the java API that facilitate interaction of a java application with the DBMS. FIRST APPROACH:
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Getting connected.  Java application calls the JDBC library.  JDBC loads a driver which talks to the database.  We can change database engines without.
Java Database Connectivity (JDBC). Introduction Database –Collection of data DBMS –Database management system –Storing and organizing data SQL –Relational.
1 Java Database Connection (JDBC) There are many industrial-strength DBMS's commercially available in the market. Oracle, DB2, and Sybase are just a few.
© Wang Bin 2004 JDBC ----Java Database Connectivity.
Java Database Connectivity (JDBC) Introduction to JDBC JDBC is a simple API for connecting from Java applications to multiple databases. Lets you smoothly.
Database Programming in Java Corresponds with Chapter 32, 33.
JDBC Olivier de Pertat. JDBC Overview JDBC is specified as an Interface API to manage and query RDBMS New standard to access RDMS : single API to access.
JDBC and Database Programming in Java. Introduction u Database Access in Java u Find out any relevant background and interest of the audience u SQL gurus?
Topic : JDBC Kaster Nurmukan. Database Access in Java Find out any relevant background and interest of the audience –SQL gurus? –Visual Basic Database.
Dr R R DOCSIT, Dr BAMU. Basic Java : Introduction to JDBC 2 Objectives of This Session State what is Java Database Connectivity State different.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
CONTROLPANEL Java.sql package This package provides the APIs for accessing and processing data which is stored in the database especially relational.
Connecting to Oracle using Java November 4, 2009 David Goldschmidt, Ph.D. David Goldschmidt, Ph.D.
JDBC Java and Databases, including Postgress. JDBC l Developed by Industry leaders l Three main goals: –JDBC should be an SQL-level API –JDBC should capitalize.
JDBC. JDBC stands for Java Data Base Connectivity. JDBC is different from ODBC in that – JDBC is written in Java (hence is platform independent, object.
JDBC  The JDBC (Java Database Connectivity) API helps a Java program to access a database in a standard way  JDBC is a specification that tells the.
1 JDBC – Java Database Connectivity. 2 Introduction to JDBC JDBC is used for accessing databases from Java applications Information is transferred from.
1 JDBC Aum Amriteshwaryai Namah. 2 2 JDBC – Java DataBase Connectivity.
JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.
Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
JDBC – Java Database Concentricity
Copyright  Oracle Corporation, All rights reserved. 6 Accessing a Database Using the JDBC API.
Java Database Connectivity (JDBC). Topics 1. The Vendor Variation Problem 2. SQL and Versions of JDBC 3. Creating an ODBC Data Source 4. Simple Database.
Java Database Connectivity. Java and the database Database is used to store data. It is also known as persistent storage as the data is stored and can.
JDBC Database Programming in Java Prepared by., Mrs.S.Amudha AP/SWE.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
Session 30 Basics of JDBC. Java Simplified / Session 30 / 2 of 33 Review A Swing menu consists of a menubar, menuitems and menus. Trees are used to depict.
JDBC CHAPTER-2. JDBC - Java Database Connectivity. JDBC from Sun Microsystems provides API or Protocol to interact with different databases. With the.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
JDBC and SQLJ CIS 612 Spring JDBC JDBC is an API that enables database access from Java programs JDBC for DB access provides ◦ Portability across.
Database Access Using JDBC BCIS 3680 Enterprise Programming.
JDBC CS 260 Database Systems. Overview  Introduction  JDBC driver types  Eclipse project setup  Programming with JDBC  Prepared statements  SQL.
CSI 3125, Preliminaries, page 1 JDBC. CSI 3125, Preliminaries, page 2 JDBC JDBC stands for Java Database Connectivity, which is a standard Java API (application.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
JDBC Part II CS 124. More about JDBC Types Statement versus PreparedStatement Timeout NULL values Meta-data close() methods Exceptions Transactions JDBC.
Basics of JDBC Session 14.
JDBC (Java Database Connectivity)
CS122B: Projects in Databases and Web Applications Winter 2016
JDBC - Java Database Connectivity. JDBC provides Java applications with access to most database systems via SQL The architecture and API closely resemble.
Ch. NoNameMarks 01AWT24 02Networking18 03JDBC20 04Swing18 05Servlet20 Advance Java Programming.
JDBC and Database Programming in Java Seree Chinodom
1 JDBC – Java Database Connectivity CS , Spring 2010.
6-1 JAVA DATABASE CONNECTOR Colorado Technical University IT420 Tim Peterson.
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
1 JDBC – Java Database Connectivity THETOPPERSWAY.COM.
Interacting with Database
JDBC – Java Database Connectivity
Web Technologies IT230 Dr Mohamed Habib.
JDBC – Java Database Connectivity
Part 4 FaaDoOEngineers.com IBM.
JDBC.
Interacting with Database
JDBC – Java Database Connectivity
Java Database Connectivity
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

Copyright © 1997 Alex Chaffee JDBC and Database Programming in Java Alexander Day Chaffee Version 1.1, 14 Feb 98

Copyright © 1997 Alex Chaffee 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?

Copyright © 1997 Alex Chaffee Agenda u Overview of Databases and Java u Overview of JDBC u JDBC APIs u Other Database Techniques

Copyright © 1997 Alex Chaffee Overview TCP/IP java.net RMI JDBC CORBA Network OS

Copyright © 1997 Alex Chaffee Vocabulary u Glossary of terms u Define the terms as used in this subject

Copyright © 1997 Alex Chaffee Part I: Overview of Databases and Java

Copyright © 1997 Alex Chaffee Databases in the Enterprise u All corporate data stored in DB u SQL standardizes format (sort of)

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee Database Architectures u Two-tier u Three-tier u N-tier

Copyright © 1997 Alex Chaffee Two-Tier Architecture u Client connects directly to server u e.g. HTTP, u Pro: u simple u client-side scripting offloads work onto the client u Con: u fat client u inflexible

Copyright © 1997 Alex Chaffee Three-Tier Architecture u Application Server sits between client and database

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee Three-Tier Cons u higher complexity u higher maintenance u lower network efficiency u more parts to configure (and buy)

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee 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)

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee Join example u People u name u homeaddress u workaddress u Addresses u id u street u state u zip

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee Part II: JDBC Overview

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee JDBC Ancestry X/OPEN ODBC JDBC

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee JDBC Drivers u Type I: “Bridge” u Type II: “Native” u Type III: “Middleware” u Type IV: “Pure”

Copyright © 1997 Alex Chaffee JDBC Drivers (Fig.) JDBC Type I “Bridge” Type II “Native” Type III “Middleware” Type IV “Pure” ODBC Driver CLI (.lib) Middleware Server

Copyright © 1997 Alex Chaffee Type I Drivers u Use bridging technology u Requires installation/configuration on client machines u Not good for Web u e.g. ODBC Bridge

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee JDBC Limitations u No scrolling cursors u No bookmarks

Copyright © 1997 Alex Chaffee 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)

Copyright © 1997 Alex Chaffee Part III: JDBC APIs

Copyright © 1997 Alex Chaffee java.sql u JDBC is implemented via classes in the java.sql package

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee 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!

Copyright © 1997 Alex Chaffee Registering a Driver u statically load driver Class.forName(“foo.bar.MyDriver”); Connection c = DriverManager.getConnection(...);  or use the jdbc.drivers system property

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee JDBC Class Usage DriverManager Driver Connection Statement ResultSet

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee 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(); }

Copyright © 1997 Alex Chaffee 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.

Copyright © 1997 Alex Chaffee Statement u A Statement object is used for executing a static SQL statement and obtaining the results produced by it.

Copyright © 1997 Alex Chaffee 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.

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee 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)

Copyright © 1997 Alex Chaffee 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)

Copyright © 1997 Alex Chaffee 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)

Copyright © 1997 Alex Chaffee Sample Database Employee IDLast NameFirst Name 1DavolioNancy 2FullerAndrew 3LeverlingJanet 4PeacockMargaret 5BuchananSteven

Copyright © 1997 Alex Chaffee SELECT Example Connection con = DriverManager.getConnection(url, "alex", " "); Statement st = con.createStatement(); ResultSet results = st.executeQuery("SELECT EmployeeID, LastName, FirstName FROM Employees");

Copyright © 1997 Alex Chaffee 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();

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee 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)

Copyright © 1997 Alex Chaffee INSERT example

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee 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()

Copyright © 1997 Alex Chaffee 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

Copyright © 1997 Alex Chaffee 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()

Copyright © 1997 Alex Chaffee JDBC Class Diagram Whoa!

Copyright © 1997 Alex Chaffee Metadata u Connection: u DatabaseMetaData getMetaData() u ResultSet: u ResultSetMetaData getMetaData()

Copyright © 1997 Alex Chaffee 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...

Copyright © 1997 Alex Chaffee 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…

Copyright © 1997 Alex Chaffee JavaBlend: Java to Relational Mapping

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

Copyright © 1997 Alex Chaffee Summary u State what has been learned u Define ways to apply training u Request feedback of training session

Copyright © 1997 Alex Chaffee Where to get more information u Other training sessions u Reese, Database Programming with JDBC and Java (O’Reilly) u u u (Author’s site)