Database Programming (JDBC)

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

Database Access from a Programming Language:

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

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

The JAVA Way: JDBC and SQLJ

SQL and Java. Database Systems Lecture 19 Natasha Alechina

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

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

DATABASDESIGN FÖR INGENJÖRER - 1DL124

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

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

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

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

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

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

CS/CE 2336 Computer Science II

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

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

1 SQL Data Types and Schemas

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

Brazil + JDBC Juin 2001, douin@cnam.fr

Part IV: Java Database Programming

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

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

SQL and programming languages

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

LSINF1124 Projet de programmation

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

Self-test Database application programming with JDBC

Java Server Pages and Java Beans

Applets, RMI, JDBC Exam Review

Java DataBase Connectivity (JDBC)

CS346: Database Programming.

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

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

Database Access Through Java Technologies

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

Security Module: SQL Injection

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

Java Programming. JDBC Spring Framework Web Services

Database System Concepts

Java and Microsoft Access SQL Tutorial

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

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

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

Chapter 4: SQL. Schema Used in Examples

More SQL: Assertions, Views, and Programming Techniques

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

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

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

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

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

Performance Tuning for the JDBC TM API

Microsoft SQL Server Features that can be used with the IBM i

create.java Printed by Jerzy Szymanski

8.1 Views and view updates 8.2 Application architectures 8.3 PL/SQL PL/pgSQL 8.4 Functions and Procedures 8.5 Triggers 8.6 Abstract Data Types

Using Netbeans and the Derby Database for Projects Contents

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

Exploiting Java Technology with the SAS Software Barbara Walters, SAS Institute Inc., Cary, NC

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

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

Matisse Java Programmer s Guide

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

SQL/PSM. Outline. Database Application Development Oracle PL/SQL. Why Stored Procedures? Stored Procedures PL/SQL. Embedded SQL Dynamic 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).

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

FileMaker 14. ODBC and JDBC Guide

FileMaker 11. ODBC and JDBC Guide

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

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Building Web Applications, Servlets, JSP and JDBC

Package sjdbc. R topics documented: February 20, 2015

Security Code Review- Identifying Web Vulnerabilities

Introduction to Triggers using SQL

Jaybird 2.1 JDBC driver. Java Programmer's Manual

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

A Brief Introduction to MySQL

Oracle to MySQL Migration

Java MySQL Connector & Connection Pool

CSE 530A Database Management Systems. Introduction. Washington University Fall 2013

Databases What the Specification Says

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

HP Vertica Integration with SAP Business Objects: Tips and Techniques. HP Vertica Analytic Database

Triggers & Packages. {INSERT [OR] UPDATE [OR] DELETE}: This specifies the DML operation.

Introduction to SAP HANA SQLScript Rich Heilman SESSION CODE: BT162

N3612: Desiderata of a C++11 Database Interface

To Java SE 8, and Beyond (Plan B)

How to Improve Database Connectivity With the Data Tools Platform. John Graham (Sybase Data Tooling) Brian Payton (IBM Information Management)

Strategic Procurement: The SAS Solution for Supplier Relationship Management Fritz Lehman, SAS Institute Inc., Cary, NC

Web Application Development on a Linux System With a DB2 Database By Alan Andrea

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

Making Oracle and JDBC Work For You

FileMaker 12. ODBC and JDBC Guide

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

SQL is capable in manipulating relational data SQL is not good for many other tasks

Programmers Reference. jconnect for JDBC 7.0

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

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

DATABASE SYSTEM CONCEPTS AND ARCHITECTURE CHAPTER 2

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

Transcription:

Database Programming (JDBC) Lecture 5 1 Outline JDBC overview JDBC API Reading: Chapter 10.5 PostgreSQL JDBC interface documentation http://jdbc.postgresql.org/documentation/head/index.html 2 1

Embedded SQL Direct SQL (= ad-hoc SQL) is rarely used In practice: SQL is embedded in some application code user interaction, devices, programming logic SQL code is embedded using special syntax into a host language 3 JDBC (Java DB Connectivity) Java application {... "SELECT... FROM... WHERE"... } DBMS 4 2

JDBC Drivers Java application JDBC- Driver manager JDBC-API Native Protocol driver JDBC- Net-driver JDBC-ODBC bridge Native API-driver DB- Middleware ODBC Client library Client library 5 Running a JDBC Application Phase Task Relevant java.sql classes Initialisation Load driver Create connection DriverManager Connection Processing Generate SQL statements Process result data Statement ResultSet etc. Termination Terminate connection Release data structures Connection Statement etc. 6 3

A Simple JDBC Application yes loaddriver getconnection createstatement execute(sql) Result handling More results? no closestatment closeconnection import java.sql.*; public class jdbctest { public static void main(string args[]){ try{ Class.forName("org.postgresql.Driver"); }}} Connection con = DriverManager.getConnection ("jdbc:postgresql://lsir-cis-pc8:5401/pcmdb", "user", "passwd"); Statement stmt = con.createstatement(); ResultSet rs = stmt.executequery ("select name, number from pcmtable where number < 2"); while(rs.next()) System.out.println(rs.getString(1) + " (" + rs.getint(2) + ")"); stmt.close() con.close(); } catch(exception e){ System.err.println(e); 7 Loading of Driver Creates an instance of the driver Registers driver in the driver manager Explicit loading String l_driver = "org.postgresql.driver"; Class.forName(l_driver); Several drivers can be loaded and registered 8 4

Implicit Driver Loading Setting system property: jdbc.drivers A colon-separated list of driver classnames. Can be set when starting the application java -Djdbc.drivers=org.postgresql.Driver application Can also be set from within the Java application Properties prp = System.getProperties(); prp.put("jdbc.drivers" "com.mimer.jdbc.driver:org.postgresql.driver"); System.setProperties(prp); The DriverManager class attempts to load all the classes specified in jdbc.drivers when the DriverManager class is initialized. 9 Addressing Database A connection is a session with one database Databases are addressed using a URL of the form "jdbc:<subprotocol>:<subname>" Examples jdbc:postgresql:database jdbc:postgresql://host/database jdbc:postgresql://host:port/database Defaults: host=localhost, port=5432 10 5

Connecting to Database Connection is established Connection con = DriverManager.getConnection(URL,USERID,PWD); Connection properties (class Properties) Close the connection con.close(); 11 Simple SQL Statements Statement object for invocation stmt = conn.createstatement(); ResultSet rset= stmt.executequery( "SELECT address,script,type FROM worklist"); ResultSet object for result processing 12 6

Impedance Mismatch Example: SQL in Java: Java uses int, char[..], objects, etc SQL uses tables Impedance mismatch = incompatible types Why not use only one language? SQL cannot do everything that the host language can do Solution: use cursors 13 Using Cursors Access to tuples ResultSet object manages a cursor for tuple access Example Statement stmt=con.createstatement(); ResultSet rset=stmt.executequery ( SELECT ); while (rset.next()) { } rset.close(); c1 c2 c3 c4 14 7

Accessing Attributes (Columns) Access to columns of a tuple Using column index or column name Example while (rset.next()) { //return the value of the first column as a String String address = rset.getstring(1); //return the value of the column type as a String String type = rset.getstring( type )... } c1 c2 c3 c4 15 More on Cursors Cursors can also modify a relation rset.updatestring("script", "ebay"); rset.updaterow(); // updates the row in the data source The cursor can be a scrolling one: can go forward, backward first(), last(), next(), previous(), absolute(5) We can determine the order in which the cursor will get tuples by the ORDER BY clause in the SQL query 16 8

Inserting a row with Cursors rs.movetoinsertrow(); // moves cursor to the insert row rs.updatestring(1, "AINSWORTH"); // updates the // first column of the insert row to be AINSWORTH rs.updateint(2,35); // updates the second column to be 35 rs.updateboolean(3, true); // updates the third column to true rs.insertrow(); rs.movetocurrentrow(); 17 Dynamic JDBC Statements Variables within SQL statement Precompiled once, multiple executions PreparedStatement for invocation PreparedStatement stmt = con.preparestatement ( "SELECT * FROM data WHERE date =?"); stmt.setdate (1, j_date); ResultSet rset = stmt.executequery(); 18 9

SQL Data Types For passing parameters to prepared statements specific SQL data types are needed Example java.util.date jd = new java.util.date(); java.sql.date j_date = new java.sql.date(jd.gettime()); 19 Update Statements Updates have no result set int result = stmt.executeupdate("delete from worklist"); Return value of executeupdate DDL-statement: always 0 DML-statement: number of tuples 20 10

Error Handling Each SQL statement can generate errors Thus each SQL method should be put into a try-block Exceptions are reported through exceptions of class SQLException 21 Import java.sql.*; public class JdbcDemo { public static void main(string[] args) { try { Class.forName(com.pointbase.jdbc.jdbcUniversalDriver); } catch (ClassNotFoundException exc){ System.out.println(exc.getMessage()); } try { Connection con = DriverManager.getConnection( jdbc:jdbc:demo", tux, penguin ); Statement stmt = con.createstatement(); ResultSet rs = stmt.executequery( SELECT * FROM data ); while (rs.next()) { process result tuples } } catch (SQLException exc) { System.out.println( SQLException: + exc.getmessage()); } } } 22 11

Metadata Metadata allows to develop schema independent applications for databases Generic output methods Type dependent applications Two types of metadata are accessible on result sets on the database 23 ResultSet Metadata java.sql.resultsetmetadata describes the structure of a result set object Information about a ResultSet object Names, types and access properties of columns 24 12

Database Metadata java.sql.databasemetadata provides information about the database (schema etc.) Information about the database Name of database Version of database List of all tables List of supported SQL types Support of transactions 25 Example ResultSet rset = stmt.executequery( SELECT * FROM data ); ResultSetMetaData rsmeta = rset.getmetadata(); int numcols = rsmeta.getcolumncount(); for (int i=1; i<=numcols; i++) { int ct = rsmeta.getcolumntype(i); String cn = rsmeta.getcolumnname(i); String ctn = rsmeta.getcolumntypename(i); System.out.println( Column # + i + : + cn + of type + ctn + (JDBC type: + ct + ) ); } 26 13