Introduction to JDBC Standard framework for dealing with tabular and generally, relational data SQL (Structured Query Language) is standardized language.

Slides:



Advertisements
Similar presentations
Java Database Connectivity (JDBC). 2/24 JDBC (Java DataBase Connectivity) - provides access to relational database systems JDBC is a vendor independent.
Advertisements

Database programming in Java An introduction to Java Database Connectivity (JDBC)
Distributed Application Development B. Ramamurthy.
1 JDBC: Part I Attribution These slides are based on three primary sources: –Sun JDBC Tutorial URL: jdbc/TOC.htmlhttp://java.sun.com/docs/books/tutorial/
JDBC Overview Autumn 2001 Lecturer: C. DeJong. Relational Databases widespread use used via SQL (Structured Query Language) freely available powerful.
1 C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California
1 Lecture 29 More on JDBC Overview  Objectives of this lecture  JDBC and its Drivers  Connecting to Databases (Java’s Connection class)  Querying a.
JDBC. In This Class We Will Cover: What SQL is What ODBC is What JDBC is JDBC basics Introduction to advanced JDBC topics.
1 Foundations of Software Design Lecture 27: Java Database Programming Marti Hearst Fall 2002.
JDBC Java API for Database Connectivity. Layout of this recitation Introduction to JDBC API JDBC Architecture Understanding the design of JDBC API –Classes.
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:
Introduction to JDBC (Java Database Connectivity).
CIS 270—App Dev II Big Java Chapter 22 Relational Databases.
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) Francisco Pajaro Saul Acosta Nahum Quezada Manuel Rubio.
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.
Think Possibility Integrating Web Applications With Databases.
Helena Pomezná, ciz034 St. skupina: L392 FEI, VŠB-TUO Ak. rok. 2002/2003 Download:
Java Database Connectivity Vijayan Sugumaran Department of DIS Oakland University.
© Wang Bin 2004 JDBC ----Java Database Connectivity.
CSE470 Software Engineering Fall Database Access through Java.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
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.
MySQL, Java, and JDBC CSE 3330 Southern Methodist University.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
Introduction to JDBC Michelle Lee, Ye Wu & Jeff Offutt SWE 432 Design and Implementation of Software for the Web.
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.
JDBC. Preliminaries Database Database Collection of data Collection of data DBMS DBMS Database management system Database management system Stores and.
Chapter 8 Databases.
Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using.
COMP201 Java Programming Topic 15: Database Connectivity JDBC Reading: Chapter 4, Volume 2.
Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.
JDBC Establish a connection with a database or access any tabular data source Send SQL statements Process the results Two major sets of interfaces: JDBC.
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.
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 CS 124. JDBC Java Database Connectivity Database Access Interface provides access to a relational database (by allowing SQL statements to be sent.
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.
12/6/2015B.Ramamurthy1 Java Database Connectivity B.Ramamurthy.
Java and Databases. JDBC Architecture Java Application JDBC API Data Base Drivers AccessSQL Server DB2InformixMySQLSybase.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
UNIT III - JDBC JDBC Overview – JDBC implementation – Connection class – Statements - Catching Database Results, handling database Queries. Networking–
DATABASE CONNECTIVITY TO MYSQL. Introduction =>A real life application needs to manipulate data stored in a Database. =>A database is a collection of.
EXAMPLE I An application showing JDBC access to Cloudscape.
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
Basics of JDBC.
Basics of JDBC Session 14.
JDBC (Java Database Connectivity)
Advanced Java Session 5 New York University School of Continuing and Professional Studies.
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
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.
R EMAINING TOPICS IN JDBC Sagun Dhakhwa. O VERVIEW Introduction to JDBC API Types of JDBC Drivers Introduction to ODBC.
Interacting with Database
Lec - 14.
HW#4 Making Simple BBS Using JDBC
Prof: Dr. Shu-Ching Chen TA: Sheng Guan
Interacting with Database
JDBC – ODBC DRIVERS.
Java Database Connectivity
Java API for Database Connectivity
JDBC Example.
Presentation transcript:

Introduction to JDBC Standard framework for dealing with tabular and generally, relational data SQL (Structured Query Language) is standardized language to interact with database A database is essentially a smart container for tables (file system). A table is a container comprised of rows (file). A row is (conceptually) a container comprised of columns (record or structure). A column is a single data item having a name, type, and value (field or variable).

ODBC Open Database Connectivity C-based interface to SQL engines Individual vendors provide drivers or bridges to their database management system (dbms) Platform specific

JDBC java.sql or JDBC Portable version of ODBC JDBC Driver converts SQL requests for a particular database

Driver Types 1: JDBC-ODBC bridge plus ODBC driver: JDBC access via ODBC drivers 2: Native-API partly-Java driver: JDBC calls converted into dbms specific code 3: JDBC-Net pure Java Driver: JDBC calls to DBMS-independent net protocol. Server converts to DBMS protocol 4: Native-protocol pure Java driver: JDBC directly to network protocol used by DBMS

JDBC Java Database Connectivity JDBC 1.0 API compatible with jdk1.1 and jdk1.2 JDBC 2.0 API compatible with jdk1.2 and greater Get JDBC API with respective JDK

JDBC 1.0 Driver DriverManager Connection Statement PreparedStatement CallableStatement ResultSet DatabaseMetaData ResultSetMetaData Types

JDBC 2.0 Core API JDBC 2.0 Optional package Performance and functionality enhancements

Steps Create the database Connect to database Create table Insert information into database Selectively retrieve information Example using J2SDKEE and Cloudscape database

Getting Started Install a driver for specific DBMS JDBC-ODBC Bridge driver more complicated. Comes with JDK, but ODBC needs some set up Install DBMS

Creating a Database DBMS-Specific Administrator Privledges Set database connection URL attribute that is passed to driver (create=true) Named database is created in DBMS default directory (J2EE_HOME/Cloudscpae)

Connecting to Database Load JDBC Driver: Class.forName( DriverClassName); Class.forName(DriverClassName).newInstance(); From Command Line: java -Djdbc.drivers=DriverClassName AJavaApp COM.cloudscape.core.RmiJdbcDriver Connect to Data source Connection con = DriverManager.getConnectio( URL, Username, Password ); Database now created

Establish a Connection Load the Driver –Class.forName("sun.jdbc.odbc.JdbcOdbcDriver "); –Class.forName("jdbc.DriverXYZ"); –Driver automatically loaded Establish Connection Connection con = DriverManager.getConnection(url, "myLogin", "myPassword");

String url = "jdbc:odbc:Fred"; Connection con = DriverManager.getConnection(url, "Fernanda", "J8"); Vendor specific subprotocol subs for “odbc” DriverManager manages all details of connection Driver class for Driver developers

Create a Table Get Statement object from connection Statement stmt = con.createStatement(); stmt.executeUpdate( "CREATE TABLE JJJJData (" + "Entry INTEGER NOT NULL, " + "Customer VARCHAR (20) NOT NULL, " + "DOW VARCHAR (3) NOT NULL, " + "Cups INTEGER NOT NULL, " + "Type VARCHAR (10) NOT NULL," + "PRIMARY KEY( Entry )" + ")" );

Insert Information Now that the table has been created, the data can be entered using the SQL INSERT statement: INSERT INTO JJJJData VALUES ( 1, 'John', 'Mon', 1, 'JustJoe' ) INSERT INTO JJJJData VALUES ( 2, 'JS', 'Mon', 1, 'Cappuccino' ) INSERT INTO JJJJData VALUES ( 3, 'Marie', 'Mon', 2, 'CaffeMocha' )... In the example program, an array named SQLData contains the actual values, with each element in a form like this: "(1, 'John', 'Mon', 1, 'JustJoe')” The program code corresponding to the INSERT statements above is: stmt.executeUpdate( "INSERT INTO JJJJData VALUES " + SQLData[i] );

import java.sql.*; public class Create4JData { static String[] SQLData = { "(1, 'John', 'Mon', 1, 'JustJoe')", "(2, 'JS', 'Mon', 1, 'Cappuccino')", "(3, 'Marie', 'Mon', 2, 'CaffeMocha')", "(4, 'Anne', 'Tue', 8, 'Cappuccino')", "(5, 'Holley', 'Tue', 2, 'MoJava')", "(6, 'jDuke', 'Tue', 3, 'Cappuccino')", "(7, 'Marie', 'Wed', 4, 'Espresso')", "(8, 'JS', 'Wed', 4, 'Latte')", "(9, 'Alex', 'Thu', 3, 'Cappuccino')", "(10, 'James', 'Thu', 1, 'Cappuccino')", "(11, 'jDuke', 'Thu', 4, 'JustJoe')", "(12, 'JS', 'Fri', 9, 'Espresso')", "(13, 'John', 'Fri', 3, 'Cappuccino')", "(14, 'Beth', 'Fri', 2, 'Cappuccino')", "(15, 'jDuke', 'Fri', 1, 'Latte')" };

public static void main(String[] args) { Connection con = null; int iRowCount = 0; Statement stmt = null; String sDriver = "COM.cloudscape.core.RmiJdbcDriver"; String sURL = "jdbc:cloudscape:rmi:jGuru;create=true"; String sUsername = "sa"; String sPassword = "admin"; try // Attempt to load the JDBC driver { // with newInstance by name Class.forName( sDriver ).newInstance(); } catch( Exception e ) // error { System.err.println( "Failed to load current driver."); return; } // end catch

try { con = DriverManager.getConnection ( sURL, sUsername, sPassword); stmt = con.createStatement(); } catch ( Exception e) { System.err.println( "problems connecting to " + sURL + ":" ); System.err.println( e.getMessage() ); if( con != null) { try { con.close(); } catch( Exception e2 ) {} } return; } // end catch

// to allow the program to be run more than once, // attempt to remove the table from the database try { stmt.executeUpdate( "DROP TABLE JJJJData" ); System.out.println( "Table JJJJData was removed."); } catch ( Exception e ) { /* don't care */ } // execute SQL commands // to create table and insert data try { stmt.executeUpdate( "CREATE TABLE JJJJData (" + "Entry INTEGER NOT NULL, " + "Customer VARCHAR (20) NOT NULL, " + "DOW VARCHAR (3) NOT NULL, " + "Cups INTEGER NOT NULL, " + "Type VARCHAR (10) NOT NULL," + "PRIMARY KEY( Entry )" + ")" );

System.out.println( "Table JJJJData was created."); for (int i = 0; i < SQLData.length; i++) { iRowCount += stmt.executeUpdate( "INSERT INTO JJJJData VALUES " + SQLData[i] ); } System.out.println( iRowCount + " Rows inserted into JJJJData."); } catch ( Exception e ) { System.err.println( "problem with SQL sent to " + sURL + ":" ); System.err.println( e.getMessage() ); }

finally { try { stmt.close(); } catch( Exception e ) {} try { con.close(); } catch( Exception e ) {} } // end finally clause } // end main } // end class Create4JData

Retrieving Information Get maximum cups of coffee consumed by returning data in decreasing order by number of cups, and then get first row: ResultSet result = stmt.executeQuery( "SELECT Entry, Customer, DOW, Cups, Type " + "FROM JJJJData " + "ORDER BY Cups DESC"); if( result.next() ) // get first row { // if data was returned sCustomer = result.getString("Customer"); iCups = result.getInt("Cups"); System.out.println( "On " + result.getString("DOW") + " 4J Customer " + sCustomer + " consumed the most coffee." +

Data Navigation while(result.next()) // for each row of data { iEntry = result.getInt("Entry"); sCustomer = result.getString("Customer"); sDOW = result.getString("DOW"); iCups = result.getInt("Cups"); iTotalCups += iCups; // increment total sType = result.getString("Type"); // Report each Customer System.out.println( iEntry + ",\t" + sCustomer + ",\t" + sDOW + ",\t" + iCups + ",\t" + sType ); }

Data Extraction Once at a row, get data column at a time: iEntry = result.getInt("Entry"); Customer = result.getString("Customer"); DOW = result.getString("DOW"); Cups = result.getInt("Cups"); TotalCups += Cups; // increment total Type = result.getString("Type");

import java.sql.*; public class Report4J { public static void main (String args[]) { Connection con = null; int iCups, iTotalCups, iEntry; Statement stmt = null; String sDriver = "COM.cloudscape.core.RmiJdbcDriver"; String sURL = "jdbc:cloudscape:rmi:jGuru"; // "jdbc:rmi:jdbc:cloudscape:jGuru;create=true"; String sUsername = "sa"; String sPassword = "admin"; String sCustomer = null, sDOW = null, sType = null;

try // Attempt to load the JDBC driver { // with newInstance Class.forName( sDriver ).newInstance(); } catch( Exception e ) // error { System.err.println( "Failed to load current driver."); return; } // end catch try { con = DriverManager.getConnection ( sURL, sUsername, sPassword); stmt = con.createStatement(); } catch ( Exception e) { System.err.println( "problems connecting to " + sURL + ":" ); System.err.println( e.getMessage() );

if( con != null) { try { con.close(); } catch( Exception e2 ) {} } return; } // end catch try { ResultSet result = stmt.executeQuery( "SELECT Entry, Customer, DOW, Cups, Type " + "FROM JJJJData " + "ORDER BY Cups DESC"); if( result.next() ) // get first row { // if data was returned sCustomer = result.getString("Customer"); iCups = result.getInt("Cups"); System.out.println( "On " + result.getString("DOW") + " 4J Customer " + sCustomer + " consumed the most coffee." +

" Cups: " + iCups + ", Type: " + result.getString("Type") + ".\n"); iTotalCups = iCups; // increment total while(result.next()) // for each row of data { iEntry = result.getInt("Entry"); sCustomer = result.getString("Customer"); sDOW = result.getString("DOW"); iCups = result.getInt("Cups"); iTotalCups += iCups; // increment total sType = result.getString("Type"); // Report each Customer System.out.println( iEntry + ",\t" + sCustomer + ",\t" + sDOW + ",\t" + iCups + ",\t" + sType ); }

// Report total System.out.println( "\n4J Cafe Total Weekly Sales: " + iTotalCups + " cups of coffee."); } // end if( result.next() ) } // end try catch (Exception e) { e.printStackTrace(); } finally { try { stmt.close(); } catch( Exception e ) {} try { con.close(); } catch( Exception e ) {} } // end finally clause } // end main } // end class Report4J