Java II--Copyright © 2001-2004 Tom Hunter. Chapter 18 JDBC.

Slides:



Advertisements
Similar presentations
5 Copyright © 2005, Oracle. All rights reserved. Accessing the Database with Servlets.
Advertisements

16 Copyright © 2005, Oracle. All rights reserved. Using JDBC to Access the Database.
Clients and Server. Clients and servers A server provides a service such as dispensing files. A client calls on a service. The distinction is not hard.
CE203 - Application Programming Autumn 2013CE203 Part 51 Part 5.
Exercises of the Tutorial on Advanced Web Programming Authors: Miroslava Mitrovic Dragan Milicev Nino.
Copyright  Oracle Corporation, All rights reserved. 2 Java and Databases: An Overview.
Java Database Connectivity (JDBC). 2/24 JDBC (Java DataBase Connectivity) - provides access to relational database systems JDBC is a vendor independent.
Basic JDBC Celsina Bignoli What is JDBC Industry standard for database- connectivity between the Java language and a wide range of.
Database programming in Java An introduction to Java Database Connectivity (JDBC)
Distributed Application Development B. Ramamurthy.
1 Design patterns Lecture 4. 2 Three Important skills Understanding OO methodology Mastering Java language constructs Recognizing common problems and.
JAVA JDBC JAVA JDBC Java Database Programming Lamiaa Said.
Introduction to JDBC (Java Database Connectivity).
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.
1 CSC 440 Database Management Systems JDBC This presentation uses slides and lecture notes available from
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.
Jaeki Song JAVA Lecture 11 Java Database Connectivity.
© 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.
Java Database Connectivity ASE. Java Database Connectivity (JDBC) l JDBC – provides an interface to Relational Data Sources l JDBC library provides the.
Database Programming in Java Corresponds with Chapter 32, 33.
Using Java with PSQL and Oracle Thanks to Drs. Raj and Liu for sharing some of these slides TRUDY: ALSO NEED SAMPLE PROGRAM.
Views, Indexes and JDBC/JSP tutorial Professor: Dr. Shu-Ching Chen TA: Haiman Tian 1.
© D. Wong  Indexes  JDBC  JDBC in J2EE (Java 2 Enterprise Edition)
Active Server Pages ASP is Microsoft’s server-side script engine for dynamically-generated web pages. Most common language used is VBScript. If you use.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
Connecting to Oracle using Java November 4, 2009 David Goldschmidt, Ph.D. David Goldschmidt, Ph.D.
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.
Index and JDBC/JSP tutorial Professor: Dr. Shu-Ching Chen TA: Hsin-Yu Ha.
JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.
JDBC Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
Chapter 8 Databases.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
Copyright  Oracle Corporation, All rights reserved. 6 Accessing a Database Using the JDBC API.
Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.
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.
Chapter 17 Accessing Databases with JDBC. JDBC JDBC provides a standard library for accessing relational databases. By using the JDBC API, you can access.
Creating competitive advantage Copyright © 2003 Enterprise Java Beans Presenter: Wickramanayake HMKSK Version:0.1 Last Updated:
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 CS 124. JDBC Java Database Connectivity Database Access Interface provides access to a relational database (by allowing SQL statements to be sent.
12/6/2015B.Ramamurthy1 Java Database Connectivity B.Ramamurthy.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
DataBases and SQL INFSY 547 Spring Course Wrap Up April 12: Complete Work on Servlets Review of Team Projects Close of Portfolio Work April 19:
16 Java Database Connectivity. 2 Understand the JDBC Understand the steps of the JDBC: 1.) Importing packages 2.) Opening a connection to a database 3.)
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 (Java Database Connectivity)
Advanced Java Session 5 New York University School of Continuing and Professional Studies.
1 Principles of Database Systems With Internet and Java Applications Today’s Topic Chapter 8: Applications Programming for Relational Databases Instructor’s.
Introduction to JDBC Instructor: Mohamed Eltabakh 1.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
CS422 Principles of Database Systems JDBC and Embedded SQL Chengyu Sun California State University, Los Angeles.
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
JDBC Statements The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enables to send SQL or PL/SQL.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
CS3220 Web and Internet Programming Database Access with JDBC
Web Technologies IT230 Dr Mohamed Habib.
CS320 Web and Internet Programming Database Access with JDBC
JDBC.
Interacting with Database
Java Database Connectivity
Using a Database with JDBC
JDBC Example.
Lecture 11 Database Connection
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

Java II--Copyright © Tom Hunter

Chapter 18 JDBC

Java II--Copyright © Tom Hunter Background: databases

Java II--Copyright © Tom Hunter Types of databases --Hierarchical --Relational --Object Relational Background: databases

Java II--Copyright © Tom Hunter Types of databases --Hierarchical-the first database, invented by IBM, called IMS. Background: databases

Java II--Copyright © Tom Hunter Types of databases --Relational-the most common, invented by IBM but first marketed by Oracle. Examples: Oracle DB2 Sybase Access * * Toy Database Background: databases

Java II--Copyright © Tom Hunter Types of databases --Object Relational-uncommon, attempts to place objects in the database. Background: databases

Java II--Copyright © Tom Hunter Relational Databases

Java II--Copyright © Tom Hunter Relational Databases: Entity Integrity Unit of the Table, smallest unit in a relational database For a table to be useful, it must enforce Entity Integrity. Entity Integrity—each row in a table can be located by using its Primary Key. 1 st Law of Relational Databases Each row in a table must have an attribute(s) that uniquely locates one row. Values in this attribute must be unique. 2 nd Law of Relational Databases The primary key attribute(s) cannot contain a null value

Java II--Copyright © Tom Hunter Relational Databases: Entity Integrity Here is a sample table, USER ID LastName FirstName Age 1 Jones Sam 32 2 Jones Angela 27 3 Smith Ann 22 4 Doe Jack 44 Primary Key—must uniquely identify a row. No nulls allowed.

Java II--Copyright © Tom Hunter Relational Databases: Entity Integrity Here is another sample table, CODE Code Message ABill Paid B Bill Overdue C Account written off DAccount closed Primary Key—must uniquely identify a row. No nulls.

Java II--Copyright © Tom Hunter Relational Databases: Referential Integrity A “foreign key” is when the primary key of one table is repeated in a second table as a non primary key. Using foreign keys, or “referential integrity” allows us to link tables. 3 rd Law of Relational Databases If you link two tables with a foreign key, any values present in the foreign-key attribute column must link back to existing primary-key values. 4 th Law of Relational Databases It is okay for a foreign key column to contain nulls.

Java II--Copyright © Tom Hunter ID LastName FirstName Age 1 Jones Sam 32 2 Jones Angela 27 3 Smith Ann 22 4 Doe Jack 44 Relational Databases: Referential Integrity ID LastName FirstName AgeCode 1 Jones Sam 32A 2 Jones Angela 27B 3 Smith Ann 22A 4 Doe Jack 44 This is the primary key for another table. This column can contain nulls. However, any values present must exist in the table that is referred to. This is a “foreign key”.

Java II--Copyright © Tom Hunter SQL Basics

Java II--Copyright © Tom Hunter SQL Basics: Structure of a SQL Statement When accessing a relational database, you must use the “Structured Query Language” (SQL) Several types of SQL: queries—for asking questions updates—for making changes insert—for adding new data DDL—for creating tables

Java II--Copyright © Tom Hunter SQL Basics: Structure of a SQL Statement Queries: SELECT statements SELECT columns FROM table; Or if we wish not to select all columns: SELECT columns FROM table WHERE expression

Java II--Copyright © Tom Hunter SQL Basics: Structure of a SQL Statement Queries: SELECT statements SELECT FirstName, LastName FROM USER WHERE ID = 2;

Java II--Copyright © Tom Hunter SQL Basics: Structure of a SQL Statement Updates: UPDATE statements UPDATE table SET column = value; Example: UPDATE table SET LastName = ‘Jones’ WHERE ID = 2;

Java II--Copyright © Tom Hunter SQL Basics: Structure of a SQL Statement Insert: INSERT statements INSERT INTO table VALUES(values); Example: INSERT INTO USER VALUES( ‘6’, ‘Anderson’, ‘Joe’, 44, ‘A’)

Java II--Copyright © Tom Hunter JDBC Basics: Connection

Java II--Copyright © Tom Hunter JDBC Basics: Connection The first step toward connecting to a database is getting a database connection. Before you can get a connection, you need a database driver. The driver makes the connection between a particular database and our Java program. These drivers are individual to each vendor’s database.

Java II--Copyright © Tom Hunter JDBC Basics: Connection To make sure your driver is available, you use the following: Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver” ); The above statement will merely ensure that the Java class containing the driver is available to our program.

Java II--Copyright © Tom Hunter JDBC Basics: Connection The statement below results in a connection to the database. import java.sql.Connection; … Connection con = DriverManager.getConnection( url, user, pass ); To create a connection using this method, it is necessary to pass three arguments to the method: username password url

Java II--Copyright © Tom Hunter JDBC Basics: url The Url is a special string of characters that finds the database. Here is a sample Url: url = —This is database specific myhostname —This is the name of the host where the database is located —This is the port on the host where the database is listening. OurDB —This is the name of the database.

Java II--Copyright © Tom Hunter JDBC Basics: Connection The DriverManager is convenient but not scalable. import java.sql.Connection; … Connection con = DriverManager.getConnection( url, user, pass ); Once you have opened a connection to the database, you must realize this is a resource. You must close the connection you opened. You must close the connection you opened.

Java II--Copyright © Tom Hunter JDBC Basics: Statements After you have a connection, you need to create a statement. There are three alternatives, each with plusses and minuses. Statement —used for a query that will be executed once. PreparedStatement —used for a query that will be executed multiple times CallableStatement —used for a query that executes a stored procedure.

Java II--Copyright © Tom Hunter JDBC Basics: Statement The Statement object is the easiest to work with. The Statement object is the least efficient. String query = “SELECT * FROM MYTABLE WHERE ID = 2”; Connection con = DriverManager.getConnection( url, user, pass ); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery( query );

Java II--Copyright © Tom Hunter JDBC Basics: PreparedStatement The PreparedStatement object requires more work. The PreparedStatement object is the most efficient. The query contains a question mark that is replaced. String query = “SELECT * FROM MYTABLE WHERE ID = ?”; Connection con = DriverManager.getConnection( url, user, pass ); PreparedStatement pstmt = con.prepareStatement( query ); pstmt.setString( 1, 494 ); ResultSet rs = pstmt.executeQuery(); This line substitutes 494 for the first question mark in the query.

Java II--Copyright © Tom Hunter JDBC Basics: CallableStatement The CallableStatement object is only appropriate for calling a stored procedure. The syntax of how you call the stored procedure is database specific. String call = “{ call myProcdure }”; Connection con = DriverManager.getConnection( url, user, pass ); CallableStatement cstmt = con.prepareCall( call ); ResultSet rs = cstmt.executeQuery();

Java II--Copyright © Tom Hunter JDBC Basics: ResultSet The ResultSet object receives the results of the query. String query = “SELECT COL1, COL2 FROM MYTABLE WHERE ID = 2”; Connection con = DriverManager.getConnection( url, user, pass ); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery( query ); while( rs.next() ) { String myCol1 = rs.getString( “COL1” ); String myCol2 = rs.getString( “COL2” ); } next() returns true while there are results These correspond to columns in the original query.

Java II--Copyright © Tom Hunter JDBC Basics: ResultSet No matter which kind of statement you choose, the ResultSet object is used the same way. close As with the Connection object, you must close your ResultSet !

Java II--Copyright © Tom Hunter try { String output = null; String query = “SELECT username from MYTABLE where pass=‘foo’ ”; Connection con = DriverManager.getConnection( url, us, pass); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery( query ); while( rs.next() ) { output = rs.getString( “username” ); } rs.close(); stmt.close(); con.close(); } catch( SQLException sql ) { System.out.println( “Uh oh…” ); } You must close these three items, in the reverse order that you opened them!

Java II--Copyright © Tom Hunter DataSource

Java II--Copyright © Tom Hunter DataSource As I said, the DriverManager is not the best choice for a production system. It doesn’t scale well. A better alternative is using a DataSource. connection pooling A DataSource offers connection pooling, where new connections are not thrown away but are instead set aside for the next time someone needs a connection.

Java II--Copyright © Tom Hunter DataSource: Need to Lookup in JNDI To use a DataSource, it is necessary to perform a lookup of the resource in something called JNDI [ JNDI = Java Naming and Directory Interface ] namesresources JNDI stores a list of names that associate with resources

Java II--Copyright © Tom Hunter DataSource: Need to Lookup in JNDI First we need to create an InitialContext so we can lookup that DataSource Context ctx = new InitialContext(); String dbJNDI = "java:comp/env/OracleJDBC"; DataSource ds = (DataSource) ctx.lookup( dbJNDI ); Connection con = ds.getConnection(); This is the name I assigned to the DataSource when I created it. Here, I’m just looking it up under the name I stored it

Java II--Copyright © Tom Hunter DataSource:Complexity of setup Using a DataSource is very valuable because it allows connection pooling. The downside of using a DataSource is the complexity of its setup. Also, each Application Server vendor has its own unique setup. You will need to learn these *. * Please refer to “Setting up a DataSource in WebSphere Application Server 5.1”