Database Access from a Programming Language:



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

The JAVA Way: JDBC and SQLJ

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

SQL and programming languages

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

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

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

1 SQL Data Types and Schemas

CS346: Database Programming.

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

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

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

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

CS/CE 2336 Computer Science II

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

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

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

Brazil + JDBC Juin 2001, douin@cnam.fr

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

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

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

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

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

Java Server Pages and Java Beans

Lesson: All About Sockets

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

Self-test Database application programming with JDBC

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

Java and Microsoft Access SQL Tutorial

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

Programming Database lectures for mathema

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

Using Netbeans and the Derby Database for Projects Contents

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

Database System Concepts

Database Access Through Java Technologies

More SQL: Assertions, Views, and Programming Techniques

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

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

Making Oracle and JDBC Work For You

Database Access via Programming Languages

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

Producing Readable Output with SQL*Plus

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

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

Java Programming. JDBC Spring Framework Web Services

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

Real SQL Programming 1

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

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

2. Follow the installation directions and install the server on ccc

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

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

Achieving Database Interoperability Across Data Access APIs through SQL Up-leveling

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

Java MySQL Connector & Connection Pool

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

Displaying Data from Multiple Tables. Chapter 4

DBX. SQL database extension for Splunk. Siegfried Puchbauer

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

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

Procedural Extension to SQL using Triggers. SS Chung

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

SQL: Programming. Introduction to Databases CompSci 316 Fall 2014

Chapter 1. Writing Basic. SQL Statements

Division of Informatics, University of Edinburgh

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

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

Security Code Review- Identifying Web Vulnerabilities

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

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

LSINF1124 Projet de programmation

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

Database Applications Recitation 10. Project 3: CMUQFlix CMUQ s Movies Recommendation System

Custom Encryption in Siebel & Siebel Web Service Security Test Guide 1.0

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

N3612: Desiderata of a C++11 Database Interface

CSI 2132 Lab 8. Outline. Web Programming JSP 23/03/2012

Database Design. Marta Jakubowska-Sobczak IT/ADC based on slides prepared by Paula Figueiredo, IT/DB

Database Extension 1.5 ez Publish Extension Manual

Security Module: SQL Injection

Package sjdbc. R topics documented: February 20, 2015

PHP Language Binding Guide For The Connection Cloud Web Services

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

Oracle8/ SQLJ Programming

Displaying Data from Multiple Tables

MyOra 3.0. User Guide. SQL Tool for Oracle. Jayam Systems, LLC

Using DOTS as Apache Derby System Test

Querying Databases Using the DB Query and JDBC Query Nodes

A Brief Introduction to MySQL

How I hacked PacketStorm ( )

FileMaker 11. ODBC and JDBC Guide

Transcription:

Database Access from a Programming Language: Java s JDBC Werner Nutt Introduction to Databases Free University of Bozen-Bolzano

2 Database Access from a Programming Language Two Approaches 1. Embedding SQL into programming language e.g., Embedded SQL for C and C++ 2. DB access via API (= call level interface ) e.g., JDBC, ODBC How do they work?

3 Approach 1: Embedded SQL SQL code occurs in program, separated by markers: EXEC SQL SELECT ranking INTO :r FROM sailors WHERE sailors.sid = 15765; r++; EXEC SQL UPDATE sailors S SET ranking = :r WHERE sailors.sid = 15765; Transfer of values between PL and SQL: use of host language variables in SQL (prefixed with : ) Compilation in two steps: 1. Preprocessor translates SQL fragments into function calls of SQL run time library (= pure C/C++ code, depends on DBMS) 2. Regular compiler for C/C++ produces executable

4 Approach 2: Call Level Interfaces Principles of JDBC Contact between Java application (= client) and DBMS (= server) is brokered by a driver Application invokes server commands by sending strings Driver translates command strings into DBMS procedure calls Drivers are vendor specific e.g., drivers for PostgreSQL, Oracle, DB2, SQL Server,... A driver manager chooses the right driver for each DBMS compiled client does not contain compiled SQL code one client can communicate with many DMBS s, even from different vendors

5 Schema of a JDBC Application Load the driver for a specific DBMS (e.g., the PostgreSQL JDBC Driver ) Establish a connection to a specific database (e.g., the PostgreSQL database wdb on the server database.inf.unibz.it) Create an abstract statement, to be sent over the connection Execute the statement by sending a Java string (e.g., "SELECT ranking FROM sailors WHERE sid = 15765") returns an object of class ResultSet Process the result set with methods of ResultSet Close statement and connection

6 import java.io.*; import java.sql.*; JDBC Example Code: Parameters //This class collects the parameters for the example... public class PostgreSqlAccess{ static PrintWriter screen = new PrintWriter(System.out,true); static BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); //Driver name: set CLASSPATH so that Java can find it! static String drivername = "org.postgresql.driver"; //URL of the DB: specifies access protocol and location of the DB static String dburl = "jdbc:postgresql://database.inf.unibz.it/mydb"; //User name: wnutt static String user = "wnutt"; } //Password for the database static String passwd = "cheerio";

7 JDBC Example Code: Queries are String import java.sql.*; import java.io.*; public class Select extends PostgreSqlAccess{ //Our example query static String selectquery = "SELECT ename, sal " + "FROM emp " + "WHERE hiredate > 01-JAN-2002 " + "ORDER BY ename"; This is the query that we want to send to the database!

8 JDBC Example Code: Accessing the Database public static void main(string args[]) throws Exception { //Load the driver Class.forName(driverName); //Establish a connection to the database via the driver Connection con = DriverManager.getConnection(dburl, user, passwd); //Create an abstract statement for the connection Statement stmt = con.createstatement(); //Execute the query and retrieve the set of results ResultSet rs = stmt.executequery(selectquery); //Process results (see below) printresults(rs,screen); } //Close statement and connection stmt.close(); con.close();

9 JDBC Example Code: Processing the Result Set } //Process the result set with methods of class ResultSet public static void printresults(resultset rs, PrintWriter pw) { try{ } //Move cursor over the result set while (rs.next()) { //Fetch components of result tuples String ename = rs.getstring(1); int sal = rs.getint(2); //Feed components into computation screen.println(ename +" \t earns " + sal + "\t per month");} //Close result set rs.close(); //Catch exceptions }catch (Exception e) { screen.println(e.tostring());}

10 JDBC Example Code: the Output >> java Select Adams earns 1100 per month Allen earns 1600 per month Blake earns 2850 per month Clark earns 2450 per month Ford earns 3000 per month James earns 950 per month Jones earns 2975 per month King earns 5000 per month Martin earns 1250 per month Miller earns 1300 per month Scott earns 3000 per month Smith earns 800 per month Turner earns 1500 per month Ward earns 1250 per month

11 JDBC Example Code: Updates (1) import java.sql.*; import java.io.*; public class Update extends PostgreSqlAccess{ //Our example update static String update = "INSERT INTO emp VALUES (" + "8492, MacGregor, Clerk, 7902, " + " 15 NOV 2001, 1800, null, 200)";

12 JDBC Example Code: Updates (2) public static void main(string args[]) throws Exception { Class.forName(driverName); Connection con = DriverManager.getConnection(dburl, user, passwd); Statement stmt = con.createstatement(); //Execute the update stmt.executeupdate(update); } } stmt.close(); con.close();

13 JDBC: Prepared Statements This is a way to define patterns of queries and updates: //Define pattern with question marks as place holders static String updatepattern = "UPDATE emp SET sal =? WHERE ename =?"; //Create instance of class PreparedStatement on connection PreparedStatement updateempsalary = con.preparestatement(updatepattern); //Fill in values for question marks updateempsalary.setint(1,2000); updateempsalary.setstring(2,"macgregor"); //Execute the instantiated pattern updateempsalary.executeupdate(); //Close the prepared statement updateempsalary.close();

14 JDBC: More Features Prepared statements: updates and queries, with methods executeupdate(), executequery() Navigation in result sets: forward, backward, skip n tuples,... Transactions defined for connections methods commit(), rollback(), setsavepoint(.),... Error handling with classes SQLException SQLWarning

15 References These slides are partly based on learning material provided by SUN Microsystems at http://java.sun.com/docs/books/tutorial/jdbc/toc.html. The examples on the slides have been run on the faculty Linux machines and reflect our local setup.