JDBC Programming: Intro

Similar documents
More Database Programming. CS157A Chris Pollett Nov. 2, 2005.

JDBC Architecture. JDBC API: This provides the application-to- JDBC Manager connection.

SQL in a Server Environment

JDBC Installation Transactions Metadata

JDBC 3.0. Java Database Connectivity. 1 Java

Lecture 2. Introduction to JDBC

Introduction to JDBC. JDBC: Java Database Connectivity. Why Access a Database with Java? Compilation. Six Steps. Packages to Import

JDBC [Java DataBase Connectivity]

e-pg Pathshala Subject: Computer Science Paper: Web Technology Module: JDBC INTRODUCTION Module No: CS/WT/26 Quadrant 2 e-text

Discuss setting up JDBC connectivity. Demonstrate a JDBC program Discuss and demonstrate methods associated with JDBC connectivity

JAVA AND DATABASES. Summer 2018

Calling SQL from a host language (Java and Python) Kathleen Durant CS 3200

Kyle Brown Knowledge Systems Corporation by Kyle Brown and Knowledge Systems Corporation

Java Database Connectivity

Questions and Answers. A. A DataSource is the basic service for managing a set of JDBC drivers.

JDBC. Oracle ODBC SP API SP API. SQL server C function calls. SQL server ODBC SP API. Oracle DSN Oracle ODBC Oracle

Enterprise Systems. Lecture 02: JDBC. Behzad BORDBAR

Unit 2 JDBC Programming

Chapter 16: Databases

JDBC Drivers Type. JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server.

CSC System Development with Java. Database Connection. Department of Statistics and Computer Science. Budditha Hettige

CMPUT 391 Database Management Systems. JDBC in Review. - Lab 2 -

COP4540 TUTORIAL PROFESSOR: DR SHU-CHING CHEN TA: H S IN-YU HA

Database Programming Overview. COSC 304 Introduction to Database Systems. Database Programming. JDBC Interfaces. JDBC Overview

Top 50 JDBC Interview Questions and Answers

ERwin and JDBC. Mar. 6, 2007 Myoung Ho Kim

Lecture 9&10 JDBC. Mechanism. Some Warnings. Notes. Style. Introductory Databases SSC Introduction to DataBases 1.

Cyrus Shahabi Computer Science Department University of Southern California C. Shahabi

Application Programming for Relational Databases

SQL: Programming Midterm in class next Thursday (October 5)

This lecture. Databases - JDBC I. Application Programs. Database Access End Users

Departamento de Lenguajes y Sistemas Informáticos

SQL: Programming. Announcements (September 25) Motivation. CPS 116 Introduction to Database Systems. Pros and cons of SQL.

Databases 2012 Embedded SQL

Database Application Development

3) execute() Usage: when you cannot determine whether SQL is an update or query return true if row is returned, use getresultset() to get the

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

The Object-Oriented Paradigm. Employee Application Object. The Reality of DBMS. Employee Database Table. From Database to Application.

Database Application Development

SQL DML and DB Applications, JDBC

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Database connectivity (II)

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal

Chapter 13 Introduction to SQL Programming Techniques

Working with Databases and Java

Database in Applica.on Development. Debapriyo Majumdar DBMS Fall 2016 Indian Statistical Institute Kolkata

Introduction to Relational Database Management Systems

Java Database Connectivity

JDBC - INTERVIEW QUESTIONS

DATABASE DESIGN I - 1DL300

Database Access with JDBC. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

Topic 12: Database Programming using JDBC. Database & DBMS SQL JDBC

Outline. Lecture 10: Database Connectivity -JDBC. Java Persistence. Persistence via Database

DataBase Lab JAVA-DATABASE CONNECTION. Eng. Haneen El-masry

Chapter 5: Advanced SQL" Chapter 5: Advanced SQL"

PESIT Bangalore South Campus

Introduction to Databases [p.3]

Embedded SQL. csc343, Introduction to Databases Renée J. Miller and Fatemeh Nargesian and Sina Meraji Winter 2018

Transactions & Concurrency Control

CSCI/CMPE Object-Oriented Programming in Java JDBC. Dongchul Kim. Department of Computer Science University of Texas Rio Grande Valley

How to program applications. CS 2550 / Spring 2006 Principles of Database Systems. SQL is not enough. Roadmap

Database Application Development

Chapter 3 DB-Gateways

Lab # 9. Java to Database Connection

Non-interactive SQL. EECS Introduction to Database Management Systems

JDBC BASIC 19/05/2012. Objectives. Java Database Connectivity. Definitions of JDBC. Part 1. JDBC basic Working with JDBC Adv anced JDBC programming

Contents. Introducing the course. Aim: to learn engineering of multi-tired web based systems. Road map of the course. Roadmap..

JDBC, Transactions. Niklas Fors JDBC 1 / 38

Database Application Development

Java Database Connectivity

INTRODUCTION TO JDBC - Revised Spring

Part I: Stored Procedures. Introduction to SQL Programming Techniques. CSC 375, Fall 2017

UNIT-3 Java Database Client/Server

BUSINESS INTELLIGENCE LABORATORY. Data Access: Relational Data Bases. Business Informatics Degree

Database Applications (15-415)

The Design of JDBC The Structured Query Language Basic JDBC Programming Concepts Query Execution Scrollable and Updatable Result Sets

Overview. Database Application Development. SQL in Application Code. SQL in Application Code (cont.)

Database Application Development

Database Application Development

Introduction to Databases

Databases and MySQL. COMP 342: Programming Methods. 16 September Databases and MySQL

Embedded SQL. csc343, Introduction to Databases Diane Horton with examples from Ullman and Widom Fall 2014

You write standard JDBC API application and plug in the appropriate JDBC driver for the database the you want to use. Java applet, app or servlets

CHAPTER 2 JDBC FUNDAMENTALS

Chapter 3 DB-Gateways

Java and the Java DataBase Connectivity (JDBC) API. Todd Kaufman April 25, 2002

DB Programming. Database Systems

INTRODUCTION TO JDBC - Revised spring

Programming in Java

Database Applications. SQL/PSM Embedded SQL JDBC

Student Number: Please fill out the identification section above as well as the one on the back page, and read the instructions below. Good Luck!

Accessing databases in Java using JDBC

MANTHLY TEST SEPTEMBER 2017 QUESTION BANK CLASS: XII SUBJECT: INFORMATICS PRACTICES (065)

Asst.Prof.Eng. IOAN-GHEORGHE RAŢIU, PhD Asst.Prof. NICOLETA DAVID. George Bariţiu University, Braşov

Instructor: Jinze Liu. Fall 2008

13 Creation and Manipulation of Tables and Databases

Chapter 10 Java and SQL. Wang Yang

Java Database Connectivity (JDBC) 25.1 What is JDBC?

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer

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

Transcription:

JDBC Programming: Intro Most interaction with DB is not via interactive interface Most people interact via 1. Application programs directly 2. Apps over the internet There are 3 general approaches to developing application programs: Special purpose languages Provided by a specific DBMS Included as part of the DBMS environment E.g., Oracle PL/SQL, MySQL s stored procedures, etc. Embedded programming DB commands embedded in standard programming language DB commands flagged by special prefix (e.g., EXEC SQL) Program preprocessed before compilation: Flagged statements id d by preprocessor Compiled by DB compiler Compiled code replaces code in source program being sent to language compiler Resulting program compiled by regular language compiler DB API DB accessed via API API is library of functions for accessing DBMS API presents standard interface to any DBMS Each DBMS must supply drivers for API Promotes portability across DBMSs Program communicates with DBMS via parameters passed to API functions 1

JDBC Programming: Intro (2) JDBC is an API Java is host language Basic program structure: 1. Import JDBC classes 2. Load JDBC drivers 3. Connect to DB 4. Access DB 5. Close session Details: 1. Import classes: import java.sql.* 2. Load drivers: 3. Connect: Class.forName("<driver_name>"); Connection <var> = DriverManager.getConnection(<url>); or Connection <var> = DriverManager.getConnection(<url>, <userid>, <passwd>); DriverM anager class provides basic services for managing JDBC drivers When getconnection called, DriverM anager tries to find appropriate driver Connection object returned on success Represents a DBMS session Used to access DB 2

4. Access: JDBC Programming: JDBC Intro (2) SQL statements sent to DB via Connection object 3 classes for doing this: (a) Statement For SQL statements without parameters Created using public abstract Statement createstatement() (b) PreparedStatement For SQL statements with parameters Usually used with precompiled statements - Statements used multiple times Created using public abstract PreparedStatement preparestatement(string sql) sql is SQL statement that may have IN parameters Parameters represented by question marks (c) CallableStatement For stored procedures Created using public abstract CallableStatement preparecall(string sql) sql may have IN and OUT parameters Includes methods for setting up and executing parameters 5. Close: Use public abstract void close() 3

JDBC Programming: JDBC Intro (3) Additional methods of Connection class: 1. setautocommit public abstract void setautocommit(boolean autocommit) Default Commits when either Statement completes Next execute occurs Last row of ResultSet returned ResultSet closed 2. commit public abstract void commit() Manual control of commits Only used when setautocommit disabled 3. rollback public abstract void rollback() Manual control of rollbacks Only used when setautocommit disabled 4. getmetadata public abstract DataBaseMetaData getmetadata() DataBaseMetaData object holds info about the DB proper 4

JDBC Programming: JDBC Non-query SQL Concerns DDL and non-select DML statements 3 ways to implement: 1. Statement 2. PreparedStatement 3. CallableObject 1. Statement objects: Cannot accept parameters To execute: public abstract int executeupdate(string sql) Returns number of rows processed (0 for DDL) sql is SQL statement Statement not terminated with semicolon 2. P reparedstatement objects: May have IN parameters Steps in use: (a) Instantiate prepared statement (b) Set parameter values (c) Execute prepared statement Statement is a string with parameter positions indicated using question marks To set parameter values: public abstract void setxxx(int parameterindex, XXX value) XXX represents any Java built-in data type parameterindex references position of given parameter (1-based) To execute: public abstract int executeupdate() Are precompiled Preferred method for statements that are called multiple times 5

Statements JDBC Programming: JDBC Statement Object Examples Statement stmt = conn.createstatement(); String query = "INSERT INTO MemberOf VALUES ( 20000, PHYS )"; try { int nrows = stmt.executeupdate(query); catch (SQLException e) { System.out.println("Error inserting into table"); while (e!= null) { System.out.println("Message:" + e.getmessage()); e = e.getnextexception(); return; stmt.close(); Prepared statements String query = "INSERT INTO MemberOf VALUES (?,?)"; PreparedStatement stmt = conn.preparestatement(query); String id = "12345"; String dept = "MATH"; try { stmt.setstring(1, id); stmt.setstring(2, dept); stmt.executeupdate(); catch (SQLException e) { System.out.println("Error inserting into table"); while (e!= null) { System.out.println("Message:" + e.getmessage()); e = e.getnextexception(); return; stmt.close(); 6

JDBC Programming: JDBC SELECT To execute: For Statement objects: public abstract ResultSet executequery(string sql) For P reparedstatement and CallableStatement objects: public abstract ResultSet executequery() ResultSet object receives results of a query To access results from ResultSet objects: 1. next public abstract boolean next() Every result set has an associated pointer Pointer points to row of returned table Initially positioned in front of, but not at, row 1 Every call of next moves pointer to next row 2. getxxx (a) public abstract XXX getxxx(int columnindex) Comparable to setxxx for retrieving column values from result set (b) public abstract XXX getxxx(string columnname) Comparable to above version, but uses column names instead of positional indices Generally slower than above Case insensitive SQL NULL represented as Java null 3. f indcolumn public abstract int findcolumn(string columnname) Return positional index of column with columnn ame 7

4. wasnull JDBC Programming: JDBC SELECT (2) public abstract boolean wasnull() Indicates whether last column read contains NULL 5. close public abstract void close() Will be closed automatically when either (a) Generating statement is closed (b) Generating statement is re-executed (c) When used to retrieve next result from a sequence of statements 8

JDBC Programming: JDBC SELECT Examples Statement stmt = conn.createstatement(); String coursedept = "CIS"; String query = "SELECT Dept, CNumber, Lname, Phone " + "FROM Faculty F, Teach T " + "WHERE F.Id = T.Id " + "AND Dept = " + coursedept + " "; ResultSet rs; String dept, cnumber, lname, phone; try { rs = stmt.executquery(query); catch (SQLException e) { System.out.println("Error executing SELECT"); while (e!= null) { System.out.println("Message:" + e.getmessage()); e = e.getnextexception(); return; System.out.println("Dept Nbr Name Phone"); System.out.println("=============================="); while (rs.next()) { dept = rs.getstring(1); cnumber = rs.getstring(2); lname = rs.getstring("lname"); phone = rs.getstring(4); //Print values of dept, cnumber, lname, and phone in field of // appropriate width stmt.close(); 9

getm etadata JDBC Programming: JDBC ResultSetMetaData public abstract ResultSetMetaData getmetadata() Returns metadata about table retrieved in a result set Methods for retrieving info from ResultSetM etadata objects: 1. getcolumncount public abstract int getcolumncount() Return number of columns in result set 2. isn ullable public abstract int isnullable(int column) Indicates whether column can have NULL Possible results: columnnonulls columnnullable columnnullableunknown 3. getcolumndisplaysize public abstract int getcolumndisplaysize(int column) Returns column max width 4. getcolumnlabel public abstract int getcolumnlabel(int column) Returns title used for display and printout of column 5. getcolumnn ame public abstract int getcolumnname(int column) 10

JDBC Programming: JDBC ResultSetMetaData 6. getcolumnt ype public abstract int getcolumntype(int column) Returns SQL type of column Represented by constant integers named by SQL types E.g., DOUBLE, INTEGER, VARCHAR,... 7. getcolumnt ypen ame public abstract String getcolumntypename(int column) Returns column s source-specific data type 8. getp recision public abstract int getprecision(int column) 9. getscale public abstract int getscale(int column) 10. gett ablename public abstract String gettablename(int column) Returns name of table for given column (empty string if not applicable) 11

JDBC Programming: JDBC ResultSet MetaData Examples Statement stmt = conn.createstatement(); String query = readquery(); //Read string from user ResultSet rs; String cname, val; int i, csize, ncols; try { rs = stmt.executequery(query); catch (SQLException e) { System.out.println("Error executing query"); while (e!= null) { System.out.println("Message:" + e.getmessage()); e = e.getnextexception(); return; ResultSetMetaData rsmd = rs.getmetadata(); ncols = rsmd.getcolumncount(); for (i = 1; i <= ncols; i++) { cname = rsmd.getcolumnname(i); csize = rsmd.getcolumndisplaysize(i); //Print name in field of csize width while (rs.next()) { for (int i = 1; i <= ncols; i++) { val = rs.getstring(i); csize = rsmd.getcolumndisplaysize(i); //Print value in field of csize width stmt.close(); 12

JDBC Programming: JDBC Error Handling JDBC provides 3 classes for handling problems: SQLException SQLWarning DataTruncation Error handling: 1. SQLException class Derived from java.lang.exception Exception objects contain: (a) Error message Retrieved using String getmessage() (b) SQL state Retrieved using String getsqlstate() (c) Error code (DBMS-specific) Retrieved using int geterrorcode() (d) Link to next exception Retrieved using SQLException getnextexception() General usage: try { //JDBC access statement catch (SQLException e) { //print general message while (e!= NULL) { System.out.println("Error msg = " + e.getmessage()); System.out.println("SQL state = " + e.getsqlstate()); System.out.println("Error code = " + e.geterrorcode()); e = e.getnextexception(); 2. SQLWarning class Subclass of SQLException Holds same info as SQLException objects 13

3. DataTruncation class JDBC Programming: JDBC Error Handling (2) Subclass of SQLWarning Contains info re truncations that occur during reads and writes of DB Read truncations usually generate warnings Write truncations generate exceptions DataTruncation objects contain following: Message Data truncation SQLState 01004 Indication of whether column or parameter is affected Access using public boolean getparameter() Index of column or parameter affected Access using public int getindex() Returns -1 if component unknown Indication of whether truncation was read or write Access using public boolean getread() Number of bytes that should have been transferred Access using public int getdatasize() Returns -1 if component unknown Number of bytes that were actually transferred Access using public int gettransfersize() Returns -1 if component unknown Link to next exception/warning object 14