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



Similar documents
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

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

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

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.

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

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

CS346: Database Programming.

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

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

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

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

Database Access from a Programming Language:

CS/CE 2336 Computer Science II

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

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

The JAVA Way: JDBC and SQLJ

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

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

Making Oracle and JDBC Work For You

Porting from Oracle to PostgreSQL

More SQL: Assertions, Views, and Programming Techniques

Java DataBase Connectivity (JDBC)

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

Package sjdbc. R topics documented: February 20, 2015

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

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

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

1 SQL Data Types and Schemas

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

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

Using SQL Server Management Studio

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

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

FileMaker 14. ODBC and JDBC Guide

Self-test Database application programming with JDBC

A Brief Introduction to MySQL

LSINF1124 Projet de programmation

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

Database Access Through Java Technologies

database abstraction layer database abstraction layers in PHP Lukas Smith BackendMedia

Using Netbeans and the Derby Database for Projects Contents

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

Part IV: Java Database Programming

Using Temporary Tables to Improve Performance for SQL Data Services

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

FileMaker 11. ODBC and JDBC Guide

Brazil + JDBC Juin 2001, douin@cnam.fr

Applets, RMI, JDBC Exam Review

ODBC Client Driver Help Kepware, Inc.

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

LAB 6: Code Generation with Visual Paradigm for UML and JDBC Integration

A basic create statement for a simple student table would look like the following.

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

Real SQL Programming 1

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

Applications of JAVA programming language to database management

Spring Data JDBC Extensions Reference Documentation

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

Programming Database lectures for mathema

MySQL for Beginners Ed 3

SQL Simple Queries. Chapter 3.1 V3.0. Napier University Dr Gordon Russell

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

CHAPTER 5 INTELLIGENT TECHNIQUES TO PREVENT SQL INJECTION ATTACKS

SQL. Short introduction

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

CSC 443 Data Base Management Systems. Basic SQL

Java Application Developer Certificate Program Competencies

Using DOTS as Apache Derby System Test

Database Programming with PL/SQL: Learning Objectives

Database Migration from MySQL to RDM Server

Talend for Data Integration guide

The release notes provide details of enhancements and features in Cloudera ODBC Driver for Impala , as well as the version history.

3.GETTING STARTED WITH ORACLE8i

Java (12 Weeks) Introduction to Java Programming Language

Java Server Pages and Java Beans

Using the SQL TAS v4

Retrieving Data Using the SQL SELECT Statement. Copyright 2006, Oracle. All rights reserved.

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

SQL Injection. The ability to inject SQL commands into the database engine through an existing application

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Database System Concepts

PHP Language Binding Guide For The Connection Cloud Web Services

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

SQL Server An Overview

Developing SQL and PL/SQL with JDeveloper

D61830GC30. MySQL for Developers. Summary. Introduction. Prerequisites. At Course completion After completing this course, students will be able to:

Database Query 1: SQL Basics

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

FileMaker 13. ODBC and JDBC Guide

Tutorial for Spring DAO with JDBC

MS ACCESS DATABASE DATA TYPES

Oracle to MySQL Migration

Security Module: SQL Injection

Transcription:

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

JDBC Acronym for Java Database Connection Provides capability to access a database server through a set of library functions Set of library functions forms a standardized Application Program Interface (API) Allows programmer to send SQL statements for execution and query retrieval Supported by most major database vendors

JDBC Program Steps Import JDBC library (java.sql.*) Load appropriate JDBC driver Create a connection object Create a statement object Submit SQL statement Process query results Close connections

JDBC: java.sql Package Library functions are contained in the java.sql package Every JDBC must import the classes in this package import java.sql.* Designed to access any database platform Un-avoidable that there will be a system-dependent component to access a specific database type Drivers are used to support communication transparency between the different vendors

JDBC Driver Java Program JDBC API JDBC driver (e.g., MySQL driver) Database (e.g., MySQL Server) direct calls using specific database protocols

JDBC Driver A communication driver is a system dependent software module that is written specifically according to a given communication protocol Different vendors can provide the same data service through different communication protocols A JDBC program must first load the desired communication driver Each system has its own way to load the driver (Biggest headache in JDBC programming)

Dealing with SQLException Most methods in the JDBC SQL library will throw SQLException Catch the exception try { < method in java.sql package > } catch ( Exception e) { < statements to execute when there is an error> } Specify throws SQLException to each method in your program - exit program upon error

DriverManager: Managing the JDBC Driver Attempt at standardization of loading the JDBC communication driver Contains methods for managing a set of JDBC drivers Methods contained in the class: static void registerdriver(driver driver) - registers the given driver with the device manager by reading in the driver code from the installed library static Connection getconnection(string url, String user, String password) - attempts to establish a connection and should only be used after the driver was registered

Registering a Driver (Textbook Way) Standard way to register a platform dependent JDBC driver is to use the registerdriver() method Example: registering the JDBC driver for Oracle: DriverManager.registerDriver( new oracle.jdbc.driver.oracledriver() ); Unfortunately not all vendors use this approach to load its JDBC driver (e.g., MySQL)

Registering a MySQL Driver Exploits Java s built-in capability to load a class Driver is loaded using the java.lang.reflect package Syntax: Class.forName( com.mysql.jdbc.driver );

Dynamic Loading Feature Java has the ability to load user-written classes dynamically into a compiled program and execute it Load a different class that has a method with the same name, you can get the behavior of the method to change Example: 2 Java classes, Add and Sub, each with a method with the same name main Compile and run each separately

Add.java public class Add { public static void main (String args[]) { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); System.out.println("Sum = " + (a + b)); } }

Sub.java public class Sub { public static void main (String args[]) { int a = Integer.parseInt(args[0]); int b = Integer.parseInt(args[1]); System.out.println("Difference = " + (a - b)); } }

Dynamic Loading: java.lang.reflect Commonly used by programs which require ability to examine or modify runtime behavior of applications Applications: create instances of objects using their fully-qualified names Debuggers & Test Tools: examine private members of classes Class browser: enumerate members of a class Drawbacks: Performance overhead Security restrictions Exposure of internals

Java Demo (DynamicLoader.java)

Location of the JDBC Driver Software Java must be able to find (locate) the JDBC Driver CLASSPATH variable must point to the SQL Java JDBC library (depends on your installation) Include the PATH to run the JDBC program Example: java -cp <location of jdbc driver library> <your program>

Create a Connection Object Network connection to a database server is established using the getconnection method in the DriverManager class Syntax: Connection SQLconnection; // variable for connection SQLconnection = DriverManager.getConnection(URL, user, password); Parameters: URL = location of the database server user = userid password = password associated with userid

JDBC: SQL Connection Connection contains a reference to the data structure that stores information on the network connection Connection must be passed to subsequent methods to communicate with the MySQL server Only need a single connection to the server URL must contain the protocol, the host name, the port number, and the database name (e.g., jdbc:mysql://cs377spring16.mathcs.emory.edu: 3306/companyDB )

Creating a Statement Object java.sql.statement class is used to execute a SQL statement (by sending it to the database) It also has buffers to receive the result tuples Before submitting a query, you must first create a Statement object for the processing of the query Syntax: Statement SQLstatement; // variable ref for obj SQLstatement = <sqlconnection>.createstatement();

Submit a SQL Query executequery method sends the SQL query using the DBMS connection to the DBMS server for processing Syntax: ResultSet rset; // reference variable for results rset = SQLstatement.executeQuery( <SQL query> ) ; Example: ResultSet rset; // reference variable for results rset = SQLstatement.executeQuery( select * from employee );

Submit a SQL Query (2) Statement object can be recycled if SQL queries are executed in serial Execute one query and read the result completely before executing next query For multiple queries at the same time, you need to create multiple Statement objects one per parallel query

Submit a SQL Update executeupdate method sends the SQL command using the DBMS connection to the DBMS server for processing SQL command maybe an INSERT, UPDATE, or DELETE statement or even creation of a table or constraint Returns an update count

Process Query Results ResultSet returns an iterable that contains all the tuples in the output relation Retrieve one tuple: rset.next() - returns null if there are no more tuples otherwise returns the next tuple Retrieve all tuples in the result set while (rset.next()!= null) { <process the tuple> }

Closing Connections Upon completion, you should close the various connections and free resources Close and free the result set: rset.close(); Close and free the Statement object SQLstatement.close(); Close and free the Connection buffer SQLconnection.close();

JDBC Demo (Employee.java)

Useful ResultSet Methods beforefirst(): moves the read cursor to the front of the ResultSet object, just before the first row (can be used to re-read the data again) first(): moves the read cursor to the first row of the ResultSet object absolute(rownumber): moves the read cursor to the row rownumber of the ResultSet object afterlast(): moves the read cursor to the end of this ResultSet object, after the last row (can be used to read the data in reverse order) last(): moves the read cursor to the last row of this Result object (can be used to find number of rows) getrow(): returns the row index of the current row

JDBC Demo (Employee2.java & Employee3.java)

Retrieve a Field in the Result Tuple Use getter methods to retrieve attribute values from the current row rset.getstring(index): returns attribute at position index as a String rset.getint(index): returns attribute at position index as int type rset.getfloat(index): returns attribute at position index as float type rset.getdouble(index): returns attribute at position index as double type

Common Java and SQL Type Equivalence Java Method getint getlong getfloat getdouble getbignum getboolean getstring getdate gettime gettimestamp getojbect SQL Type INTEGER BIG INT REAL / FLOAT DOUBLE DECIMAL BIT / BOOLEAN VARCHAR / CHAR DATE TIME TIMESTAMP any type

Metadata About ResultSet ResultSetMetData class contains meta information about the ResultSet Methods to retrieve/obtain the meta data Variables to store values of the meta data Syntax: ResultSet rset; rset = SQLstatement.executeQuery( <SQL query >); ResultSetMetaData metadata; metadata = rset.getmetadata();

Useful ResultSetMetaData Methods int getcolumncount(): returns the number of columns in the tuples of the ResultSet String getcolumnname(int columnindex): returns the name of the column whose index is specified String getcolumntype(int columnindex): returns the integer code for the data type of the attribute whose index is specified (see java.lang.types for the codes) String getcolumntypename(int columnindex): returns the type of column whose index is specified

Useful ResultSetMetaData Methods (2) int getcolumndisplaysize(int columnindex): returns the display width (number of characters needed to display the value) of the attribute whose index is specified int getprecision(int columnindex): returns the number of digits of the field/column whose index is specified - data type must be numeric int getscale(int columnindex): returns the number of decimal places of the field/column whose index is specified - data type must be numeric String getcolumnclassname(int columnindex): returns the name of the Java class (e.g., java.lang.string ) for the attribute whose index is specified

JDBC Demo (MetaData.java)