Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java.

Slides:



Advertisements
Similar presentations
CE203 - Application Programming Autumn 2013CE203 Part 51 Part 5.
Advertisements

Java Database Connectivity (JDBC). 2/24 JDBC (Java DataBase Connectivity) - provides access to relational database systems JDBC is a vendor independent.
1 JDBC Java Database Connectivity. 2 Agenda Relational Database Model Structured Query Language JDBC  API Overview  JDBC Architecture  JDBC Features.
Java Database Connectivity (JDBC). Introduction Structured Query Language –Queries relational databases –Can write Java programs to use SQL queries Host.
JDBC Overview Autumn 2001 Lecturer: C. DeJong. Relational Databases widespread use used via SQL (Structured Query Language) freely available powerful.
V OOP: JDBC1 V Week 8 v Objective –to give some background on JDBC to help with the lab exercises Fall, 2002 Introduction to Java Database.
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.
Adv. CoE Lab: JDBC 1 Advanced Computer Engineering Lab Objective – –to give some background on JDBC to help with the lab exercises , Semester.
JDBC Java API for Database Connectivity. Layout of this recitation Introduction to JDBC API JDBC Architecture Understanding the design of JDBC API –Classes.
JAVA JDBC JAVA JDBC Java Database Programming Lamiaa Said.
Lab: JDBC 1 Computer Engineering Lab III v Objective –to give some background on JDBC to help with the lab exercises , Semester 1,
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).
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
1 CSC 440 Database Management Systems JDBC This presentation uses slides and lecture notes available from
Java Database Connectivity (JDBC) Francisco Pajaro Saul Acosta Nahum Quezada Manuel Rubio.
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 Vijayan Sugumaran Department of DIS Oakland University.
Jaeki Song JAVA Lecture 11 Java Database Connectivity.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java/jsp program to connect to any database.
© Wang Bin 2004 JDBC ----Java Database Connectivity.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
Java Database Connectivity ASE. Java Database Connectivity (JDBC) l JDBC – provides an interface to Relational Data Sources l JDBC library provides the.
Java Utility Classes CS 21b. Some Java Utility Classes Vector Hashtable StringTokenizer * import java.util.*;
CIS 270—Application Development II Chapter 25—Accessing Databases with JDBC.
Georgia Institute of Technology Making Text for the Web part 5 Barb Ericson Georgia Institute of Technology March 2006.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
Computer Engineering Lab
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 Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
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.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
Copyright  Oracle Corporation, All rights reserved. 6 Accessing a Database Using the JDBC API.
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.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
Database Access Using JDBC BCIS 3680 Enterprise Programming.
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.
Basics of JDBC.
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.
Web Programming Assistant Professor Xiaozhong Liu
Introduction to JDBC Instructor: Mohamed Eltabakh 1.
JSP/Database Connectivity Instructor: Dr. M. Anwar Hossain.
Java Database Connectivity JDBC. Open Database Connectivity developed by Microsoft to provide interaction with databases using SQL. Use the JDBC-ODBC.
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. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java program to connect to any database.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
JSP and DB.
CS3220 Web and Internet Programming Database Access with JDBC
Note: To complete the examples in this section you need access to a database!! Most of the examples work for any database with JDBC drivers. However, connecting.
Java Access to RDB Relational databases (RDBs) dominate today, due to:
Lec - 14.
JDBC Database Management Database connectivity
CS320 Web and Internet Programming Database Access with JDBC
Advanced Web Automation Using Selenium
Objectives In this lesson, you will learn about:
Interacting with Database
Using a Database with JDBC
JDBC Example.
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

Overview 1. What is JDBC? 2. The JDBC-ODBC Bridge 3. JDBC Pseudocode 4. simpJDBC.java

5. Meta Data 6. Books.mdb as an ODBC Data Source

What is JDBC? What is JDBC? JDBC provides a set of classes for Java with a standard SQL database access interface. JDBC provides a set of classes for Java with a standard SQL database access interface. Allow programs to access to a wide range of relational databases which follow the ANSI SQL-2 standard Allow programs to access to a wide range of relational databases which follow the ANSI SQL-2 standard Provides an API for database "drivers" to make actual connections and transactions to databases. Provides an API for database "drivers" to make actual connections and transactions to databases.

JDBC in Use Java program connectivity data processing utilities JDBC driver for Oracle driver For MySQL jdbc-odbc bridge odbc driver

The JDBC-ODBC Bridge ODBC (Open Database Connectivity) is a Microsoft standard from the mid 1990’s. ODBC (Open Database Connectivity) is a Microsoft standard from the mid 1990’s. It is an API that allows C/C++ programs to execute SQL inside databases It is an API that allows C/C++ programs to execute SQL inside databases ODBC is supported by many products. ODBC is supported by many products.

The JDBC-ODBC bridge allows Java code to use the C/C++ interface of ODBC The JDBC-ODBC bridge allows Java code to use the C/C++ interface of ODBC –it means that JDBC can access many different database products The layers of translation (Java --> C -- > SQL) can slow down execution. The layers of translation (Java --> C -- > SQL) can slow down execution.

The JDBC-ODBC bridge comes free with the JDK: The JDBC-ODBC bridge comes free with the JDK: –called sun.jdbc.odbc.JdbcOdbcDriver The ODBC driver for Microsoft Access comes with MS Office The ODBC driver for Microsoft Access comes with MS Office –so it is easy to connect Java and Access

JDBC Drivers list of drivers (freeware, shareware, and commercial) list of drivers (freeware, shareware, and commercial) Sun Microsystems JDBC home page Sun Microsystems JDBC home page –Java.sun.com/products/jdbc SQL materials SQL materials –

JDBC PseudoCode All JDBC programs do the following: All JDBC programs do the following: –1) load the JDBC driver –2) Specify the name and location of the database being used –3) Connect to the database with a Connection object Continued

–4) Execute a SQL query using a Statement object –5) Get the results in a ResultSet object –6) Finish by closing the ResultSet, Statement and Connection objects

Pseudocode Diagram DriveManagerConnectionStatementResultSet creates Driver SQL data make link to driver

DriveManager It is responsible for establishing the connection to the database through the driver. It is responsible for establishing the connection to the database through the driver. e.g. e.g. Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn = DriveManager.getConnection(url);

Name the Database The name and location of the database is given as a URL The name and location of the database is given as a URL –the details of the URL vary depending on the type of database that is being used

ODBC Database URL jdbc:odbc: //host.domain.com: 1511 /data/file The comms protocol The machine holding the database. The port used for the connection. The path to the database on the machine e.g. jdbc:odbc:Books

Statement Object The Statement object provides a ‘workspace’ where SQL queries can be created, executed, and results collected. The Statement object provides a ‘workspace’ where SQL queries can be created, executed, and results collected. e.g. e.g. Statement st = conn.createStatement(): ResultSet rs = st.executeQuery( “ select * from Students” ); : st.close();

ResultSet Object Stores the results of a SQL query. Stores the results of a SQL query. A ResultSet object is similar to a ‘table’ of answers, which can be examined by moving a ‘pointer’ (cursor). A ResultSet object is similar to a ‘table’ of answers, which can be examined by moving a ‘pointer’ (cursor). Continued

Cursor operations: Cursor operations: –first(), last(), next(), previous(), etc. Typical code: Typical code: while( rs.next() ) { // process the row; } John Mark Paul Peter cursor 3

Demo Set up Access Database Set up Access Database Set up ODBC source Set up ODBC source

Make a Access Database “JDBCStudent”

Add Data to Students Table

Press “Add’ to add a data source and select Microsoft Access Driver (*.mdb). Press “Finish”. Press “Add’ to add a data source and select Microsoft Access Driver (*.mdb). Press “Finish”. Add ODBC datasource ControlPanel: administrator tools. ODBC Data Sources Administrator

Type in a source name, description, and press “Select” to browse to set the path to the JDBCStduent.mdb file.

Username & Password The database’s link to the outside (e.g. its ODBC interface) must be configured to have a login and password The database’s link to the outside (e.g. its ODBC interface) must be configured to have a login and password

ClicK Advanced ClicK Advanced Type in a username and password (guest). Click “Ok” Type in a username and password (guest). Click “Ok”

simpJDBC.java // simpJDBC.java import java.sql.*; public class JdbcSimple { private java.sql.Connection connection; public JdbcSimple(){ String url = "jdbc:odbc:cs483"; String username = "anonymous"; String password = "guest";

try { // load the JDBC-ODBC Bridge driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // connect to db using DriverManager Connection conn = DriverManager.getConnection( url, username, password ); // Create a statement object Statement statement = conn.createStatement(); // Execute the SQL query ResultSet rs = statement.executeQuery( "SELECT lastName, firstName FROM Authors" ); :

// Print the result set while( rs.next() ) System.out.println( rs.getString("lastName") + ", " + rs.getString("firstName") ); // Close down statement.close(); conn.close(); } :

catch ( ClassNotFoundException cnfex ) { System.err.println( "Failed to load JDBC/ODBC driver." ); cnfex.printStackTrace(); System.exit( 1 ); // terminate program } catch ( SQLException sqlex ) { System.err.println( sqlex ); sqlex.printStackTrace(); } } // end of main() } // end of simpJDBC class

Accessing a ResultSet The ResultSet class contains many methods for accessing the value of a column of the current row The ResultSet class contains many methods for accessing the value of a column of the current row –can use the column name or position –e.g. get the value in the lastName column: rs.getString("lastName") Continued

The ‘tricky’ aspect is that the values are SQL data, and so must be converted to Java types/objects. The ‘tricky’ aspect is that the values are SQL data, and so must be converted to Java types/objects. There are many methods for accessing/converting the data, e.g. There are many methods for accessing/converting the data, e.g. –getString(), getDate(), getInt(), getFloat(), getObject()

Meta Data Meta data is the information about the database: Meta data is the information about the database: –e.g. the number of columns, the types of the columns –meta data is the schema information IDNameCourseMark 007JamesCS JetMath10080 meta data

Accessing Meta Data The getMetaData() method can be used on a ResultSet object to create its meta data object. The getMetaData() method can be used on a ResultSet object to create its meta data object. e.g. e.g. ResultSetMetaData md = rs.getMetaData();

Using Meta Data int numCols = md.getColumnCount(); for (int i = 0; i <= numCols; i++) { if (md.getColumnType(i) == Types.CHAR) System.out.println( md.getColumnName(i) ) }

More Meta Data Methods getTableName() getTableName() getPrecision() getPrecision() –number of decimal digits in the column isSigned() isSigned() –returns true if column has signed numbers isCurrency() isCurrency() etc. etc.

Summary: Setting up the Data Source Create a new Database Create a new Database –AddressBookDB ID, firstName, lastName,... ID, firstName, lastName,... Create a DSN for the Database Create a DSN for the Database –DSN: Data Source Name tells your program which database to use! tells your program which database to use! Done in the ODBC control panel Done in the ODBC control panel the DSN is what will be required in the URL to the Database for ODBC!! the DSN is what will be required in the URL to the Database for ODBC!!

Summary: Steps in using JDBC Load the appropriate JDBC driver Load the appropriate JDBC driver –Done using dynamic class loading in Java Open a Connection to the Database Open a Connection to the Database Create a new query as an SQL Statement Create a new query as an SQL Statement Execute the query Execute the query Process the ResultSet Process the ResultSet –for database meta-data and the records Close the Statement Close the Statement Close the ResultSet Close the ResultSet Close the database connection Close the database connection

Creating JDBC statements A statement object is what sends your SQL statement to DBMS. You create a statement object and execute it. The method to use is executeQuery or executeUpdate. A statement object is what sends your SQL statement to DBMS. You create a statement object and execute it. The method to use is executeQuery or executeUpdate. – Statement stmt = dbConnection.createStatement(); – String sqlState = new String ( "SELECT FirstName, LastName FROM ATable"); – ResultSet myResults = stmt.executeQuery( sqlState );

Statement Statement stmt = connection.createStatement(); Statement stmt = connection.createStatement(); stmt.executeQuery(String); stmt.executeQuery(String); stmt.executeUpdate(String); stmt.executeUpdate(String);

PreparedStatement Better performance Better performance String sql = "select ? from atable"; String sql = "select ? from atable"; PreparedStatement stmt = PreparedStatement stmt = connection.prepareStatement(sql); connection.prepareStatement(sql); stmt.setString(1, ”acolumn"); stmt.setString(1, ”acolumn"); ResultSet rs = stmt.execute(); ResultSet rs = stmt.execute(); The "1" replaces the first "?" in the statement The "1" replaces the first "?" in the statement A "2" would replace the second "?" in the statement A "2" would replace the second "?" in the statement

ResultSet Queries return results in a ResultSet Queries return results in a ResultSet Provides row-by-row access to results Provides row-by-row access to results Must call next() before getting data Must call next() before getting data Can get data out by data type Can get data out by data type Can refer to columns by index or by name Can refer to columns by index or by name

Getting and processing the results while( myResults.next()) while( myResults.next()) { System.out.println(myResults.getString(1) + " " + myResults.getString(2)); System.out.println(myResults.getString(1) + " " + myResults.getString(2)); }

Example: getTable try { String query = "SELECT * FROM Authors"; statement = connection.createStatement(); resultSet = statement.executeQuery( query ); displayResultSet( resultSet ); statement.close(); } catch ( SQLException sqlex ) { sqlex.printStackTrace(); }

Display Table // position to first record boolean moreRecords = rs.next(); if ( ! moreRecords ) { return; } // get column heads ResultSetMetaData rsmd = rs.getMetaData(); for ( int i = 1; i <= rsmd.getColumnCount(); ++i ) columnHeads.addElement( rsmd.getColumnName( i ) ); // get row data do { rows.addElement( getNextRow( rs, rsmd ) ); } while ( rs.next() );

Get a row Vector currentRow = new Vector(); for ( int i = 1; i <= rsmd.getColumnCount(); ++i ) switch( rsmd.getColumnType( i ) ) { case Types.VARCHAR: currentRow.addElement( rs.getString( i ) ); break; case Types.INTEGER: currentRow.addElement( new Long( rs.getLong( i ) ) ); break; default: System.out.println( "Type was: " + rsmd.getColumnTypeName( i ) ); }

ResultSetMetaData ResultSetMetaData md = rs.getMetaData(); ResultSetMetaData md = rs.getMetaData(); md.getColumnName(int); md.getColumnName(int); md.getColumnType(int); md.getColumnType(int); md.getColumnCount(); md.getColumnCount();

Find in a Table Statement statement =connection.createStatement(); String query = "SELECT * FROM addresses " + String query = "SELECT * FROM addresses " + "WHERE lastname = '" + "WHERE lastname = '" + fields.last.getText() + "'"; fields.last.getText() + "'"; ResultSet rs = statement.executeQuery( query ); ResultSet rs = statement.executeQuery( query ); display( rs ); display( rs );

Update a Table Statement statement = connection.createStatement(); if ( ! fields.id.getText().equals( "" ) ) { String query = "UPDATE addresses SET " + "firstname='" + fields.first.getText() + "', lastname='" + fields.last.getText() + "' WHERE id=" + fields.id.getText(); int result = statement.executeUpdate( query ); if ( result == 1 ) output.append( "\nUpdate successful\n" ); else { output.append( "\nUpdate failed\n" ); }

Another Database Books.mdb Publishers PublisherID PublisherName Titles ISBN Title EditionNumber YearPublished Description PublisherID AuthorISBN ISBN AuthorID Authors AuthorID FirstName LastName YearBorn

Building large information systems Client Client server server Database Database