COSC344 Database Theory and Applications. Java and SQL. Lecture 12



Similar documents
CS 377 Database Systems SQL Programming. Li Xiong Department of Mathematics and Computer Science Emory University

Services. Relational. Databases & JDBC. Today. Relational. Databases SQL JDBC. Next Time. Services. Relational. Databases & JDBC. Today.

Database Programming. Week *Some of the slides in this lecture are created by Prof. Ian Horrocks from University of Oxford

JDBC (Java / SQL Programming) CS 377: Database Systems

CS/CE 2336 Computer Science II

Java DataBase Connectivity (JDBC)

The JAVA Way: JDBC and SQLJ

Database Access from a Programming Language: Database Access from a Programming Language

Database Access from a Programming Language:

What is ODBC? Database Connectivity ODBC, JDBC and SQLJ. ODBC Architecture. More on ODBC. JDBC vs ODBC. What is JDBC?

Chapter 9 Java and SQL. Wang Yang wyang@njnet.edu.cn

Why Is This Important? Database Application Development. SQL in Application Code. Overview. SQL in Application Code (Contd.

Java and Databases. COMP514 Distributed Information Systems. Java Database Connectivity. Standards and utilities. Java and Databases

CS346: Database Programming.

Part IV: Java Database Programming

Course Objectives. Database Applications. External applications. Course Objectives Interfacing. Mixing two worlds. Two approaches

Chapter 13. Introduction to SQL Programming Techniques. Database Programming: Techniques and Issues. SQL Programming. Database applications

DEVELOPING MULTITHREADED DATABASE APPLICATION USING JAVA TOOLS AND ORACLE DATABASE MANAGEMENT SYSTEM IN INTRANET ENVIRONMENT

More SQL: Assertions, Views, and Programming Techniques

CHAPTER 3. Relational Database Management System: Oracle. 3.1 COMPANY Database

Overview. Database Application Development. SQL in Application Code (Contd.) SQL in Application Code. Embedded SQL. Embedded SQL: Variables

Applets, RMI, JDBC Exam Review

Database Application Development. Overview. SQL in Application Code. Chapter 6

1 SQL Data Types and Schemas

How To Create A Table In Sql (Ahem)

SQL and Java. Database Systems Lecture 19 Natasha Alechina

Using SQL Server Management Studio

JDBC. It is connected by the Native Module of dependent form of h/w like.dll or.so. ex) OCI driver for local connection to Oracle

Chapter 1 JDBC: Databases The Java Way! What Is The JDBC? The JDBC Structure ODBC s Part In The JDBC Summary

SQL Programming. CS145 Lecture Notes #10. Motivation. Oracle PL/SQL. Basics. Example schema:

Database Access Through Java Technologies

Figure 1. Accessing via External Tables with in-database MapReduce

Database Migration from MySQL to RDM Server

Making Oracle and JDBC Work For You

A Brief Introduction to MySQL

CSC 443 Data Base Management Systems. Basic SQL

LSINF1124 Projet de programmation

How To Use The Database In Jdbc.Com On A Microsoft Gdbdns.Com (Amd64) On A Pcode (Amd32) On An Ubuntu (Amd66) On Microsoft

SQL. Short introduction

Performance Tuning for the JDBC TM API

Programming Database lectures for mathema

MAKING ORACLE AND SQLJ WORK FOR YOU John Jay King, King Training Resources

An Introduction to SQL Injection Attacks for Oracle Developers. January 2004 INTEGRIGY. Mission Critical Applications Mission Critical Security

Using DOTS as Apache Derby System Test

DATABASDESIGN FÖR INGENJÖRER - 1DL124

Oracle to MySQL Migration

Self-test Database application programming with JDBC

create.java Printed by Jerzy Szymanski

ODBC Client Driver Help Kepware, Inc.

FileMaker 11. ODBC and JDBC Guide

Chapter 9, More SQL: Assertions, Views, and Programming Techniques

Database System Concepts

How To Let A Lecturer Know If Someone Is At A Lecture Or If They Are At A Guesthouse

Apéndice C: Código Fuente del Programa DBConnection.java

Application Development A Cocktail of Java and MCP. MCP Guru Series Dan Meyer & Pramod Nair

Microsoft SQL Server Connector for Apache Hadoop Version 1.0. User Guide

4 Logical Design : RDM Schema Definition with SQL / DDL

Oracle8/ SQLJ Programming

Supplement IV.C: Tutorial for Oracle. For Introduction to Java Programming By Y. Daniel Liang

MYSQL DATABASE ACCESS WITH PHP

Java Programming with Oracle JDBC

Real SQL Programming 1

Brazil + JDBC Juin 2001, douin@cnam.fr

Accesssing External Databases From ILE RPG (with help from Java)

HyperSQL User Guide. HyperSQL Database Engine (HSQLDB) 2.1. Edited by The HSQL Development Group, Blaine Simpson, and Fred Toussi

SQL Server An Overview

Abstract. Introduction. Web Technology and Thin Clients. What s New in Java Version 1.1

Package sjdbc. R topics documented: February 20, 2015

WS-JDBC. (Web Service - Java DataBase Connectivity) Remote database access made simple: 1.

Java Application Developer Certificate Program Competencies

MS ACCESS DATABASE DATA TYPES

Unifying the Global Data Space using DDS and SQL

Intro to Embedded SQL Programming for ILE RPG Developers

Advanced SQL. Jim Mason. Web solutions for iseries engineer, build, deploy, support, train

Porting from Oracle to PostgreSQL

Chapter 4: SQL. Schema Used in Examples

FileMaker 14. ODBC and JDBC Guide

database abstraction layer database abstraction layers in PHP Lukas Smith BackendMedia

Information Technology NVEQ Level 2 Class X IT207-NQ2012-Database Development (Basic) Student s Handbook

WHITE PAPER. An Introduction to SQL Injection Attacks for Oracle Developers

SQL Server Array Library László Dobos, Alexander S. Szalay

Supplement IV.D: Tutorial for MS Access. For Introduction to Java Programming By Y. Daniel Liang

Conventional Files versus the Database. Files versus Database. Pros and Cons of Conventional Files. Pros and Cons of Databases. Fields (continued)

4 Simple Database Features

Real SQL Programming. Embedded SQL Call-Level Interface Java Database Connectivity

SQL and programming languages

CS2506 Operating Systems II Lab 8, 8 th Tue/03 /2011 Java API

Microsoft SQL connection to Sysmac NJ Quick Start Guide

1 File Processing Systems

Relational databases and SQL

To create a universal SQL client for accessing local or remote database ( 35.2). To execute SQL statements in a batch mode ( 35.3).

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer

An Oracle White Paper August, Oracle JDBC Memory Management

An Oracle White Paper June Migrating Applications and Databases with Oracle Database 12c

2. Accessing Databases via the Web

14 Triggers / Embedded SQL

Embedded SQL. Unit 5.1. Dr Gordon Russell, Napier University

How To Use A Sas Server On A Java Computer Or A Java.Net Computer (Sas) On A Microsoft Microsoft Server (Sasa) On An Ipo (Sauge) Or A Microsas (Sask

Statement Level Interface. Call Level Interface. Static SQL. Status. Connections. Transactions. To connect to an SQL database, use a connect statement

Database Support for XML

Transcription:

COSC344 Database Theory and Applications Lecture 12: Java and SQL COSC344 Lecture 12 1

Last Lecture Trigger Overview This Lecture Java & SQL Source: Lecture notes, Textbook: Chapter 12 JDBC documentation Program examples Next 2 Lectures C & SQL PHP & SQL COSC344 Lecture 12 2

Database Design Process miniworld DBMS-independent DBMS-specific Functional Requirements Functional Analysis High-level Transaction Specification Application Program Design Transaction Implementation Requirements Collection and Analysis data requirements Conceptual Design Conceptual Schema (in a high-level data model) Logical Design (Data Model Mapping) Logical (Conceptual) Schema (in a high-level data model) Physical Design Internal Schema Application Programs COSC344 Lecture 12 3

Database Programming Approaches Using a library of database functions A library of APIs for accessing databases from programs SQL commands are included as parameters in function calls Java DataBase Connectivity (JDBC) --- this lecture Embedding database commands in a general-purpose programming language Embed SQL statements in the host programming language A special prefix (EXEC SQL) for identification A precompiler to extract the SQL for processing in DBMS Pro*C/C++ Precompiler --- next lecture Designing a brand-new language Applications with intensive database interactions COSC344 Lecture 12 4

What is JDBC? JDBC: Java DataBase Connectivity A standard for connecting from Java to relational databases A library of Java APIs for tool/database developers Implemented through the standard java.sql interfaces Allows individual providers to implement and extend the standard with their own JDBC drivers. Goals: 100% Pure Java SQL-Level Simple and high performance COSC344 Lecture 12 5

JDBC Architecture Java Application JDBC Library Driver Java application calls JDBC library. JDBC loads a driver. Driver communicates with a particular database. An application can work with several databases by using different drivers. COSC344 Lecture 12 6

JDBC Drivers JDBC Thin Driver Pure Java driver on the client-side Requires no Oracle software on client-side Implements SQL*Net on top of Java sockets Supports the TCP/IP protocol Applets and applications JDBC OCI Driver OCI - Oracle Call Interface Requires Oracle client installation Written in a combination of Java and C Needs OCI libraries, C-entry points, Oracle Net, COSC344 Lecture 12 7

JDBC Drivers (cont.) JDBC Thin Driver Java Sockets Oracle Database Java Engine JDBC OCI Driver OCI Library SQL Engine PL/SQL Engine Sever-Side Thin Driver JDBC Server-Side Internal Driver KPRB C Library Oracle Database COSC344 Lecture 12 8

JDBC Drivers (cont.) JDBC Server-Side Thin Driver Offers the same functionality as Thin driver on client-side Runs inside Oracle Database Accesses a remote database from an Oracle Database Accesses another session from a Java stored procedure JDBC Sever-Side Internal Driver Supports any Java code that runs inside Oracle Database Java Virtual Machine(JVM) communicates with SQL Engine Fully consistent with the client-side driver Only support Java 1.5 COSC344 Lecture 12 9

Basic Steps Connect to the database How to Use JDBC? - Register the driver and set up a connection Create a statement Execute SQL Process the result set Close result set and statement objects Close the connection Interfaces and APIs java.sql package Classes and Methods - http://docs.oracle.com/javase/7/docs/api/java/sql/package-summary.html COSC344 Lecture 12 10

Packages Importing Packages Connect to Database Regardless of which Oracle JDBC driver you use, include the import statements shown in Table 2 1 at the beginning of your program. Table 2 1 Import Statements for JDBC Driver Import statement import java.sql.*; import java.math.*; import oracle.jdbc.*; import oracle.jdbc.pool.*; import oracle.sql.*; Provides Standard JDBC packages. The BigDecimal and BigInteger classes. You can omit this package if you are not going to use these classes in your application. Oracle extensions to JDBC. This is optional. OracleDataSource. Oracle type extensions. This is optional. The Oracle packages listed as optional provide access to the extended functionality provided by Oracle JDBC drivers, but are not required for the example presented in this section. Note: It is better to import only the classes your application needs, rather than using the wildcard asterisk (*). This guide uses the COSC344 Lecture 12 11

Connect to Database (cont.) DriverManager Class Manage a set of JDBC drivers Methods (1) static void registerdriver (Driver driver) //Registers the given driver with the DriverManager (2) static void deregisterdriver(driver driver) //Drops a driver from the DriverManager's list (3) static Connection getconnection(string url) //Attempts to establish a connection to the given database URL (4) static Connection getconnection(string url, String user, String password) //Attempts to connect to the given database URL with user name and password COSC344 Lecture 12 12

JDBC URLs JDBC uses a URL to identify the database connection. jdbc: <subprotocol> :<subname> Protocol Subprotocol Database identifier jdbc: oracle: <driver>: @<database> Our Lab jdbc: oracle: thin: @ silver:1521:cosc344 COSC344 Lecture 12 13

Connect to Database (example) // Read pass.dat UserPass login = new UserPass(); String user = login.getusername(); String pass = login.getpassword(); String host = "silver"; // Register the driver and connect to Oracle DriverManager.registerDriver(new oracle.jdbc.driver.oracledriver()); String url = "jdbc:oracle:thin:@" + host + ":1521:cosc344"; Connection con = null; con = DriverManager.getConnection(url, user, pass); COSC344 Lecture 12 14

Create Statement Statement Interface Send the SQL statement to the database Return the results produced Need an active connection to create a statement Methods supporting Statement (Connection Interface) Statement createstatement() - a simple SQL statement with no parameters PreparedStatement preparestatement() - a SQL statement that is executed frequently with or without parameters CallableStatement preparecall() - a CallableStatement object for calling database stored procedures COSC344 Lecture 12 15

Execute SQL Three methods to execute an SQL statement ResultSet executequery() - Executes the SQL query and returns the data in a table (ResultSet) ResultSet results = stmt.executequery( SELECT * FROM employee ); int executeupdate() - Execute INSERT, UPDATE, or DELETE Statements - The return is the number of rows affected in the database - Support Data Definition Language (DDL) statements CREATE TABLE, DROP TABLE, and ALTER TABLE int rows = stmt.executeupdate ( DELETE FROM employees + WHERE dno = 4 ); COSC344 Lecture 12 16

Execute SQL (cont.) boolean execute() - Generic method for executing stored procedures and prepared statements - May or may not return a ResultSet (statement.getresultset) - Two or more result sets may be produced - Rarely used, exception for multiple return result sets COSC344 Lecture 12 17

Using Statement Statement ResultSet int Execute SQL (example) stmt = con.createstatement(); reset = stmt.executequery( SELECT * FROM employee ); rows = statement.executeupdate ( DELETE FROM employee + WHERE dno = 4 ) Using PreparedStatement PreparedStatement pstmt = con.preparestatement( INSERT INTO + employee(ssn, lname) values (?,?) ); //Add Bob as employee number 1500 pstmt.setint (1,150000000); //The first? Is for ssn pstmt.setstring(2, Bob ); //The second? Is for lname pstmt.executeupdate(); COSC344 Lecture 12 18

Process the Result ResultSet Interface A table representing a result set generated by a query A ResultSet maintains a cursor pointing its current row of data Provides a set of methods to manipulate the data in ResultSet Uses a while loop and next() to iterate through the ResultSet while (rset.next()) {. } Cursor Management Methods boolean first() boolean next() boolean previous() boolean last() boolean isfirst() boolean islast() COSC344 Lecture 12 19

Process the Result (cont.) Data Retrieval Methods byte getbyte(int columnindex) double getdouble(int columnindex) int getint(int columnindex) Date getdate(int columnindex) Data Update Methods void updateint(int columnindex, int x) void updatenull(int columnindex) void insertrow() More Methods refer to ResultSet Interface in java.sql package COSC344 Lecture 12 20

Process the Result (cont.) ResultSetMetaData Interface Used to get information about the types and properties of the columns in a ResultSet object ResultSet reset = stmt.executequery( SELECT * FROM employee ); ResultSetMetaData rsmd = reset.getmetadata(); Methods (1) int getcolumncount(); (2) String getcolumnlabel(int column) (3) String getcolumnname(int column) (4) int getcolumntype(int column) (5) boolean isnullable(int column) (6) boolean isreadonly(int column) COSC344 Lecture 12 21

JDBC Data Types JDBC Type Java Type JDBC Type Java Type BIT boolean NUMERIC DECIMAL BigDecimal TINYINT byte DATE Java.sql.Date SMALLINT short TIME INTEGER int TIMESTAMP BIGINT long CLOB Clob REAL float BLOB Blob FLOAT DOUBLE BINARY VARBINARY LONGVARBINARY CHAR VARCHAR LONGVARCHAR double ARRAY Array DISTINCT byte[] STRUCT Struct String REF Java.sql.Timestamp Mapping of underlying type COSC344 Lecture 12 22 Ref JAVA_OBJECT Underlying java class

Close the ResultSet object reset.close(); Close the Statement object stmt.close(); Close the connection con.close(); Close the Connection COSC344 Lecture 12 23

JDBC Exceptions SQLException: provides information on a database access error or other errors try { // Java-SQL statement } catch (SQLException e){ quit(e.message()); } private void quit (String message){ System.err.println(message); System.exit(1); } COSC344 Lecture 12 24

JDBC Exceptions (cont.) try catch finally statement try { } //Register the driver and connect to Oracle //Execute SQL //Process the result catch (SQLException e){ } //Process exception finally { } //close connection COSC344 Lecture 12 25

Examples A query example Retrieves from the EMPLOYEE table the first and last names and department number of all employees whose first name begins with a specified letter. An update example Updates the salary field for a specified employee. Ask for the SSN of an employee and a new salary. Updates the salary and commits. An example showing the use of wasnull() The use of various data types and the use of wasnull() Source code /coursework/344/pickup/oracle-java COSC344 Lecture 12 26

Useful References Oracle's JDBC documentation on the course web page under Resources JDBC Package java.sql http://docs.oracle.com/javase/7/docs/api/java/sql/package-summary.html Reese, G; Database Programming with JDBC and JAVA, O'Reilly, 2nd edition Example programs are in /coursework/344/pickup/oraclejava COSC344 Lecture 12 27