The JAVA Way: JDBC and SQLJ



Similar documents
Database Access from a Programming Language: Database Access from a Programming Language

Database Access from a Programming Language:

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

CS346: Database Programming.

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

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

SQL and programming languages

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

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

SQL and Java. Database Systems Lecture 19 Natasha Alechina

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

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

1 SQL Data Types and Schemas

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

CS/CE 2336 Computer Science II

Applets, RMI, JDBC Exam Review

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

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

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

Brazil + JDBC Juin 2001, douin@cnam.fr

Java Server Pages and Java Beans

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

Java and Microsoft Access SQL Tutorial

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

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

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

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

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

Java MySQL Connector & Connection Pool

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

Java Programming. JDBC Spring Framework Web Services

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

More SQL: Assertions, Views, and Programming Techniques

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

LSINF1124 Projet de programmation

Week 5: Embedded SQL. Embedded SQL 4. Application Program. Interactive vs. Non-Interactive SQL. Update Statements

TECH TUTORIAL: EMBEDDING ANALYTICS INTO A DATABASE USING SOURCEPRO AND JMSL

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

A Brief Introduction to MySQL

Security Module: SQL Injection

Using Netbeans and the Derby Database for Projects Contents

Database System Concepts

Making Oracle and JDBC Work For You

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

SQL: Programming. Introduction to Databases CompSci 316 Fall 2014

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

Oracle8/ SQLJ Programming

Comparing the Effectiveness of Penetration Testing and Static Code Analysis

TABLE OF CONTENTS...2 INTRODUCTION...3 APPLETS AND APPLICATIONS...3 JAVABEANS...4 EXCEPTION HANDLING...5 JAVA DATABASE CONNECTIVITY (JDBC)...

Security Code Review- Identifying Web Vulnerabilities

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

ASP.NET Programming with C# and SQL Server

Object Oriented Design with UML and Java. PART XVIII: Database Technology

Using JML to protect Java code against SQL injection. Johan Janssen June 26, 2007

7 Web Databases. Access to Web Databases: Servlets, Applets. Java Server Pages PHP, PEAR. Languages: Java, PHP, Python,...

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

Part IV: Java Database Programming

Working With Derby. Version 10.2 Derby Document build: December 11, 2006, 7:06:09 AM (PST)

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

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

Mimer SQL. Programmer s Manual. Version 8.2 Copyright 2000 Mimer Information Technology AB

Java DB Performance. Olav Sandstå Sun Microsystems, Trondheim, Norway Submission ID: 860

Using Temporary Tables to Improve Performance for SQL Data Services

Package sjdbc. R topics documented: February 20, 2015

database abstraction layer database abstraction layers in PHP Lukas Smith BackendMedia

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

Self-test Database application programming with JDBC

DBMS SQL JDBC 1. Integrated data

public class ResultSetTable implements TabelModel { ResultSet result; ResultSetMetaData metadata; int num cols;

FileMaker 11. ODBC and JDBC Guide

CSc 230 Software System Engineering FINAL REPORT. Project Management System. Prof.: Doan Nguyen. Submitted By: Parita Shah Ajinkya Ladkhedkar

Advanced Object Oriented Database access using PDO. Marcus Börger

Chapter 4: SQL. Schema Used in Examples

Oracle Database: SQL and PL/SQL Fundamentals

Java and RDBMS. Married with issues. Database constraints

Introduction Web Portal Main Page Group Management Create group Modify Group Member List... 5

SQL/PSM. Outline. Database Application Development Oracle PL/SQL. Why Stored Procedures? Stored Procedures PL/SQL. Embedded SQL Dynamic SQL

Embedded SQL programming

Unit 3. Retrieving Data from Multiple Tables

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

Programming Database lectures for mathema

N3458: Simple Database Integration in C++11

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

Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach ) The JdbcTemplate. Class...

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

How I hacked PacketStorm ( )

Developing SQL and PL/SQL with JDeveloper

Oracle Database: SQL and PL/SQL Fundamentals NEW

SQLITE C/C++ TUTORIAL

12 Embedding SQL in Programming languages

Spring Data JDBC Extensions Reference Documentation

Java DataBase Connectivity (JDBC)

SQL and Programming Languages. SQL in Programming Languages. Applications. Approaches

Oracle Database: SQL and PL/SQL Fundamentals

NGASI AppServer Manager SaaS/ASP Hosting Automation for Cloud Computing Administrator and User Guide

Database Access Through Java Technologies

Transcription:

The JAVA Way: JDBC and SQLJ David Toman School of Computer Science University of Waterloo Introduction to Databases CS348 David Toman (University of Waterloo) JDBC/SQLJ 1 / 21

The JAVA way to Access RDBMS JDBC: Java version of ODBC http://java.sun.com/products/jdbc/ Hamilton, et al: JDBC Database Access with JAVA. A Tutorial and annotated Reference. Addison Wesley 1997. SQLJ: Embedded SQL in Java http://www.service-architecture.com/ database/articles/sqlj.html Examples, etc., again courtesy of IBM: http://www.software.ibm.com/data/db2/java/ David Toman (University of Waterloo) JDBC/SQLJ 2 / 21

JDBC Overview JAVA API patterned after ODBC ) uses OO features to handle sets by iterators Standardized ) should work with any RDBMS What does it do for us? 1 establishes connection with the database 2 manages SQL statements 3 processes results/diagnostic messages David Toman (University of Waterloo) JDBC/SQLJ 3 / 21

JDBC Drivers and Connections Connection to the DBMS is made using two pieces of software: 1 JDBC driver (supplied by the DBMS vendor) COM.ibm.db2.jdbc.app.DB2Driver: IBM DB2 jdbc:oracle:oci8:@database : ORACLE 8 sun.jdbc.odbc.jdbcodbcdriver : JDBC to ODBC ) use Class.forName to load it. 2 JDBC Driver Manager (in JDK1.1) ) makes the actual connection: DriverManager.getConnection("jdbc:db2:db") ) uses an URL to identify the database ) picks the right driver based on the URL David Toman (University of Waterloo) JDBC/SQLJ 4 / 21

JDBC Example // DB2 UDB JDBC Samples // // (c) Copyright International Business Machines // Corporation, 1996, 1997. All Rights Reserved. import java.sql.*; class Appl { static { try { // register the driver with DriverManager Class.forName("COM.ibm.db2.jdbc.app.DB2Driver"); catch (Exception e) { e.printstacktrace(); David Toman (University of Waterloo) JDBC/SQLJ 5 / 21

JDBC (connection) public static void main(string argv[]) { Connection con = null; // URL is jdbc:db2:dbname String url = "jdbc:db2:cs448"; try { if (argv.length == 0) { // connect with default id/password con = DriverManager.getConnection(url); else if (argv.length == 2) { String userid = argv[0]; String passwd = argv[1]; // connect with user-provided username and password con = DriverManager.getConnection(url, userid, passwd); else { System.out.println("\nUse: java Appl [name passwd]\n"); System.exit(0); David Toman (University of Waterloo) JDBC/SQLJ 6 / 21

Statements et al. get a statement : stmt = con.createstatement() or stmt = con.preparestatement(string) where String may contain parameters (?) supply input parameters : stmt.setxxx(i,val) (or stmt.setnull()) and execute it: ResultSet stmt.executequery() int = stmt.executeupdate() David Toman (University of Waterloo) JDBC/SQLJ 7 / 21

Errors Much nicer than in ODBC/Embedded SQL in C: use JAVA Exception handling mechanisms. The methods used in JDBC may throw SQLException ) you HAVE to catch it. Provides: 1 SQL state: exception.getsqlstate() 2 Text Message: exception.getmessage() 3 Vendor code: exception.geterrorcode() 4... to get next exception : exception.getnextexception() David Toman (University of Waterloo) JDBC/SQLJ 8 / 21

Retrieving Answers JDBC returns answers to queries using ResultSet: essentially an implicit cursor. returned by rs = stmt.executequery() get tuple/no more tuples: boolean rs.next() get value of attributes: XXX rs.getxxx(int) (by column number) or XXX rs.getxxx(string) (by attribute name) close: rs.close() No indicator variables: uses JAVA s NULL. David Toman (University of Waterloo) JDBC/SQLJ 9 / 21

Retrieving Answers JDBC returns answers to queries using ResultSet: essentially an implicit cursor. returned by rs = stmt.executequery() get tuple/no more tuples: boolean rs.next() get value of attributes: XXX rs.getxxx(int) (by column number) or XXX rs.getxxx(string) (by attribute name) close: rs.close() No indicator variables: uses JAVA s NULL. David Toman (University of Waterloo) JDBC/SQLJ 9 / 21

JDBC query // get a statement handle Statement stmt = con.createstatement(); // retrieve data from the database ResultSet rs = stmt.executequery("select * from publication"); System.out.println("Received results:"); // display the result set // rs.next() returns false when there are no more rows while (rs.next()) { String a = rs.getstring(1); String str = rs.getstring(2); System.out.print(" pubid= " + a); System.out.print(" title= " + str); System.out.print("\n"); rs.close(); stmt.close(); David Toman (University of Waterloo) JDBC/SQLJ 10 / 21

JDBC update // get a statement handle stmt = con.preparestatement("update author set name = SHILI where aid =?"); //set up the paremeter(s) stmt.setint(1,1); // update the database int rowsupdated = stmt.executeupdate(); System.out.println("Changed "+rowsupdated+" row(s)."); stmt.close(); con.close(); catch( Exception e ) { e.printstacktrace(); David Toman (University of Waterloo) JDBC/SQLJ 11 / 21

Transactions and Connections Transactions managed by database connection: con.commit() ) commits the transaction con.rollback() ) aborts the transaction con.close() ) closes the database connection (and releases DBMS resources) David Toman (University of Waterloo) JDBC/SQLJ 12 / 21

SQLJ Overview Embedded SQL for Java Only Static SQL (use JDBC for dynamic SQL) Type checking ) allows disconnected operation Magic keyword in SQLJ: #sql <sqlj command> Error handling: ) exception-based (same as in JDBC) SQLJ compiles foo.sqlj to foo.java. ) connects to the database ) uses exemplar schema David Toman (University of Waterloo) JDBC/SQLJ 13 / 21

Connections and Contexts embedded SQL implicitly talks to a context ) essentially a database connection ) Exemplar Schema for every context context declarations #sql context MyContext; contexts may be used explicitly: #sql [MyContext]... ; context omitted! default context David Toman (University of Waterloo) JDBC/SQLJ 14 / 21

SQLJ Example // DB2 UDB SQLJ Samples // // (c) Copyright International Business Machines // Corporation, 1998. All Rights Reserved. import java.sql.*; import sqlj.runtime.*; #sql iterator App_Cursor1 (String empno, String firstnme) ; #sql iterator App_Cursor2 (String) ; class App { static { try { // register the driver with DriverManager Class.forName("COM.ibm.db2.jdbc.app.DB2Driver"); catch (Exception e) { e.printstacktrace(); David Toman (University of Waterloo) JDBC/SQLJ 15 / 21

SQLJ (cont.) public static void main(string argv[]) { try { Connection con = null; // URL is jdbc:db2:dbname String url = "jdbc:db2:cs448"; DefaultContext ctx = DefaultContext.getDefaultContext(); if (ctx == null) { try { // connect with default id/password con = DriverManager.getConnection(url); ctx = new DefaultContext(con); catch (SQLException e) { System.out.println("Error: no default context"); System.err.println(e) ; System.exit(1); DefaultContext.setDefaultContext(ctx); David Toman (University of Waterloo) JDBC/SQLJ 16 / 21

SQLJ Statements Embedded SQL statements: #sql [context] { embedded sql ; ) embedded sql must be a static SQL statement ) host variables connect SQL and JAVA David Toman (University of Waterloo) JDBC/SQLJ 17 / 21

SQLJ update try { // update the database #sql { UPDATE author set name = :string where aid = :aid ; // rollback the update #sql { ROLLBACK work ; catch( Exception e ) { e.printstacktrace(); David Toman (University of Waterloo) JDBC/SQLJ 18 / 21

Cursors, Iterators, etc. iterator object declarations #sql iterator Iter (a1,..., ak); used for queries: where ai is a type and identifier (name) #sql Iter = { SELECT b1,...,bk FROM... ; binding of columns: 1 positional: #sql { FETCH :Iter INTO :v1,...,:vk ; more rows: Iter.endFetch() not true 2 named: value of column a i : vi = Iter.ai() next row: Iter.next() is true David Toman (University of Waterloo) JDBC/SQLJ 19 / 21

SQLJ query try { #sql iterator cursor1(string pubid, String title); #sql cursor1 = { SELECT pubid, title from publicaion ; System.out.println("Received results:"); while (cursor1.next()) { str1 = cursor1.pubid(); str2 = cursor1.title(); System.out.print (" pubid= " + str1); System.out.print (" title= " + str2); System.out.print ("\n"); cursor1.close(); #sql { SELECT count(*) into :count1 from author ; System.out.println("There are "+count1+" authors."); catch( Exception e ) { e.printstacktrace(); David Toman (University of Waterloo) JDBC/SQLJ 20 / 21

Summary SQL in JAVA: static: SQLJ + SQLJ precompiler ) adopts most of static embedded SQL dynamic: JDBC ) responsible for the rest... SQLJ and JDBC cooperate Cursors handled by Iterators Errors are handled by JAVA Exceptions David Toman (University of Waterloo) JDBC/SQLJ 21 / 21