Topic : JDBC Kaster Nurmukan. Database Access in Java Find out any relevant background and interest of the audience –SQL gurus? –Visual Basic Database.

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 JDBC "Java Database Connectivity". 2 Getting Started Guide: etstart/GettingStartedTOC.fm.html java.sql.
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.
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?
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.
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.
Copyright © 1997 Alex Chaffee JDBC and Database Programming in Java Alexander Day Chaffee Version 1.1, 14 Feb 98.
Interacting with Database
JDBC 15-Apr-18.
JDBC Database Management Database connectivity
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
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

Topic : JDBC Kaster Nurmukan

Database Access in Java Find out any relevant background and interest of the audience –SQL gurus? –Visual Basic Database Forms?

Overview of Databases and Java Overview of JDBC JDBC APIs Other Database Techniques

Glossary of terms Define the terms as used in this subject

Copyright © 1997 Alex Chaffee

All corporate data stored in DB SQL standardizes format (sort of)

Write once, run anywhere –Multiple client and server platforms Object-relational mapping –databases optimized for searching/indexing –objects optimized for engineering/flexibility Network independence –Works across Internet Protocol Database independence –Java can access any database vendor Ease of administration –zero-install client

Two-tier Three-tier N-tier

Client connects directly to server e.g. HTTP, Pro: –simple –client-side scripting offloads work onto the client Con: –fat client –inflexible

Application Server sits between client and database

flexible: can change one part without affecting others can connect to different databases without changing code specialization: presentation / business logic / data management can cache queries can implement proxies and firewalls

higher complexity higher maintenance lower network efficiency more parts to configure (and buy)

Design your application using as many “tiers” as you need Use Object-Oriented Design techniques Put the various components on whatever host makes sense Java allows N-Tier Architecture, especially with RMI and JDBC

Hierarchical –obsolete (in a manner of speaking) –any specialized file format can be called a hierarchical DB Relational (aka SQL) (RDBMS) –row, column –most popular Object-relational DB (ORDBMS) –add inheritance, blobs to RDB –NOT object-oriented -- “object” is mostly a marketing term Object-oriented DB (OODB) –data stored as objects –high-performance for OO data models

invented by Dr. E.F.Codd data stored in records which live in tables maps row (record) to column (field) in a single table “relation” (as in “relational”) means row to column (not table to table)

you can associate tables with one another allows data to nest allows arbitrarily complicated data structures not object-oriented

People –name –homeaddress –workaddress Addresses –id –street –state –zip

Structured Query Language Standardized syntax for “querying” (accessing) a relational database Supposedly database-independent Actually, there are important variations from DB to DB

INSERT INTO table ( field1, field2 ) VALUES ( value1, value2 ) –inserts a new record into the named table UPDATE table SET ( field1 = value1, field2 = value2 ) WHERE condition –changes an existing record or records DELETE FROM table WHERE condition –removes all records that match condition SELECT field1, field2 FROM table WHERE condition –retrieves all records that match condition

Transaction = more than one statement which must all succeed (or all fail) together If one fails, the system must reverse all previous actions Also can’t leave DB in inconsistent state halfway through a transaction COMMIT = complete transaction ROLLBACK = abort

Copyright © 1997 Alex Chaffee

SQL-Level 100% Pure Java Keep it simple High-performance Leverage existing database technology –why reinvent the wheel? Use strong, static typing wherever possible Use multiple methods to express multiple functionality

X/OPEN ODBC JDBC

ApplicationJDBCDriver Java code calls JDBC library JDBC loads a driver Driver talks to a particular database Can have more than one driver -> more than one database Ideal: can change database engines without changing any application code

Type I: “Bridge” Type II: “Native” Type III: “Middleware” Type IV: “Pure”

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

Use bridging technology Requires installation/configuration on client machines Not good for Web e.g. ODBC Bridge

Native API drivers Requires installation/configuration on client machines Used to leverage existing CLI libraries Usually not thread-safe Mostly obsolete now e.g. Intersolv Oracle Driver, WebLogic drivers

Calls middleware server, usually on database host Very flexible -- allows access to multiple databases using one driver Only need to download one driver But it’s another server application to install and maintain e.g. Symantec DBAnywhere

100% Pure Java -- the Holy Grail Use Java networking libraries to talk directly to database engines Only disadvantage: need to download a new driver for each database engine e.g. Oracle, mSQL

No scrolling cursors No bookmarks

ODBC –Requires configuration (odbc.ini) RDO, ADO –Requires Win32 OODB –e.g. ObjectStore from ODI JavaBlend –maps objects to tables transparently (more or less)

JDBC is implemented via classes in the java.sql package

Driver d = new foo.bar.MyDriver(); Connection c = d.connect(...); Not recommended, use DriverManager instead Useful if you know you want a particular driver

DriverManager tries all the drivers Uses the first one that works When a driver class is first loaded, it registers itself with the DriverManager Therefore, to register a driver, just load it!

statically load driver Class.forName(“foo.bar.MyDriver”); Connection c = DriverManager.getConnection(...); or use the jdbc.drivers system property

DriverManager –Loads, chooses drivers Driver –connects to actual database Connection –a series of SQL statements to and from the DB Statement –a single SQL statement ResultSet –the records returned from a Statement

DriverManager Driver Connection Statement ResultSet

jdbc:subprotocol:source each driver has its own subprotocol 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

Connection getConnection (String url, String user, String password) Connects to given JDBC URL with given user name and password Throws java.sql.SQLException returns a Connection object

A Connection represents a session with a specific database. Within the context of a Connection, SQL statements are executed and results are returned. Can have multiple connections to a database –NB: Some drivers don’t support serialized connections –Fortunately, most do (now) Also provides “metadata” -- information about the database, tables, and fields Also methods to deal with transactions

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(); }

Statement createStatement() –returns a new Statement object PreparedStatement prepareStatement(String sql) –returns a new PreparedStatement object CallableStatement prepareCall(String sql) –returns a new CallableStatement object Why all these different kinds of statements? Optimization.

A Statement object is used for executing a static SQL statement and obtaining the results produced by it.

ResultSet executeQuery(String) –Execute a SQL statement that returns a single ResultSet. int executeUpdate(String) –Execute a SQL INSERT, UPDATE or DELETE statement. Returns the number of rows changed. boolean execute(String) –Execute a SQL statement that may return multiple results. Why all these different kinds of queries? Optimization.

A ResultSet provides access to a table of data generated by executing a Statement. Only one ResultSet per Statement can be open at once. The table rows are retrieved in sequence. A ResultSet maintains a cursor pointing to its current row of data. The 'next' method moves the cursor to the next row. –you can’t rewind

boolean next() –activates the next row –the first call to next() activates the first row –returns false if there are no more rows void close() –disposes of the ResultSet –allows you to re-use the Statement that created it –automatically called by most Statement methods

Type getType(int columnIndex) –returns the given field as the given type –fields indexed starting at 1 (not 0) Type getType(String columnName) –same, but uses name of field –less efficient int findColumn(String columnName) –looks up column index given column name

String getString(int columnIndex) boolean getBoolean(int columnIndex) byte getByte(int columnIndex) short getShort(int columnIndex) int getInt(int columnIndex) long getLong(int columnIndex) float getFloat(int columnIndex) double getDouble(int columnIndex) Date getDate(int columnIndex) Time getTime(int columnIndex) Timestamp getTimestamp(int columnIndex)

String getString(String columnName) boolean getBoolean(String columnName) byte getByte(String columnName) short getShort(String columnName) int getInt(String columnName) long getLong(String columnName) float getFloat(String columnName) double getDouble(String columnName) Date getDate(String columnName) Time getTime(String columnName) Timestamp getTimestamp(String columnName)

In SQL, NULL means the field is empty Not the same as 0 or “” In JDBC, you must explicitly ask if a field is null by calling ResultSet.isNull(column)

Employee IDLast NameFirst Name 1DavolioNancy 2FullerAndrew 3LeverlingJanet 4PeacockMargaret 5BuchananSteven

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

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();

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

Times in SQL are notoriously unstandard Java defines three classes to help java.sql.Date –year, month, day java.sql.Time –hours, minutes, seconds java.sql.Timestamp –year, month, day, hours, minutes, seconds, nanoseconds –usually use this one

use executeUpdate if the SQL contains “INSERT” or “UPDATE” Why isn’t it smart enough to parse the SQL? Optimization. executeUpdate returns the number of rows modified executeUpdate also used for “CREATE TABLE” etc. (DDL)

Transactions are not explicitly opened and closed Instead, the connection has a state called AutoCommit mode if AutoCommit is true, then every statement is automatically committed default case: true

Connection.setAutoCommit(boolean) if AutoCommit is false, then every statement is added to an ongoing transaction you must explicitly commit or rollback the transaction using Connection.commit() and Connection.rollback()

Hint: for a large threaded database server, create a Connection Manager object It is responsible for maintaining a certain number of open connections to the database When your applications need a connection, they ask for one from the CM’s pool Why? Because opening and closing connections takes a long time Warning: the CM should always setAutoCommit(false) when a connection is returned

Prepared Statements –SQL calls you make again and again –allows driver to optimize (compile) queries –created with Connection.prepareStatement() Stored Procedures –written in DB-specific language –stored inside database –accesed with Connection.prepareCall()

Whoa!

Connection: –DatabaseMetaData getMetaData() ResultSet: –ResultSetMetaData getMetaData()

Copyright © 1997 Alex Chaffee What's the number of columns in the ResultSet? What's a column's name? What's a column's SQL type? What's the column's normal max width in chars? What's the suggested column title for use in printouts and displays? What's a column's number of decimal digits? Does a column's case matter? Is the column a cash value? Will a write on the column definitely succeed? Can you put a NULL in this column? Is a column definitely not writable? Can the column be used in a where clause? Is the column a signed number? Is it possible for a write on the column to succeed? and so on...

Copyright © 1997 Alex Chaffee What tables are available? What's our user name as known to the database? Is the database in read-only mode? If table correlation names are supported, are they restricted to be different from the names of the tables? and so on…

Copyright © 1997 Alex Chaffee

Scrollable result set Batch updates Advanced data types –Blobs, objects, structured types Rowsets –Persistent JavaBeans JNDI Connection Pooling Distributed transactions via JTS

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

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