CS/CE 2336 Computer Science II



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

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

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

Part IV: Java Database Programming

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

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

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

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

Database Access from a Programming Language:

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

SQL and Java. Database Systems Lecture 19 Natasha Alechina

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

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

The JAVA Way: JDBC and SQLJ

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

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

LSINF1124 Projet de programmation

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

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

Database Access Through Java Technologies

Applets, RMI, JDBC Exam Review

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

Abstract. Introduction. Web Technology and Thin Clients. What s New in Java Version 1.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

To create a universal SQL client for accessing local or remote database ( 35.2). To execute SQL statements in a batch mode ( 35.3).

Performance Tuning for the JDBC TM API

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

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

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

Self-test Database application programming with JDBC

Using Netbeans and the Derby Database for Projects Contents

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

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

1 SQL Data Types and Schemas

SQL and programming languages

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

CS346: Database Programming.

FileMaker 11. ODBC and JDBC Guide

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

FileMaker 14. ODBC and JDBC Guide

Database access and JDBC. Tecniche di Programmazione A.A. 2013/2014

Java DataBase Connectivity (JDBC)

Java and RDBMS. Married with issues. Database constraints

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

Database System Concepts

Database Access with JDBC

IMS Users Group. The Right Change SQL-Based Middleware. Mike McKee CONNX Solutions.

FileMaker 12. ODBC and JDBC Guide

FileMaker 13. ODBC and JDBC Guide

Applications of JAVA programming language to database management

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

Web Development with Java EE JavaBeans and JDBC

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

Package sjdbc. R topics documented: February 20, 2015

SQL. Short introduction

David M. Kroenke and David J. Auer Database Processing 11 th Edition Fundamentals, Design, and Implementation. Chapter Objectives

Introduction. Introduction: Database management system. Introduction: DBS concepts & architecture. Introduction: DBS versus File system

ACCESSING DATABASES WITH JDBC. Topics in This Chapter

Java Server Pages and Java Beans

WS-JDBC. (Web Service - Java DataBase Connectivity) Remote database access made simple: 1.

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

Introduction: Database management system

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

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

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

ASP.NET Programming with C# and SQL Server

Exchanger XML Editor - Data Import

Oracle8/ SQLJ Programming

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

Making Oracle and JDBC Work For You

A DATABASE-BACKED CLIENT-SERVER APPLICATION IN JAVA FOR CUSTOMER BOOKINGS

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

How I hacked PacketStorm ( )

and what does it have to do with accounting software? connecting people and business

Introduction to HP ArcSight ESM Web Services APIs

Demystified CONTENTS Acknowledgments xvii Introduction xix CHAPTER 1 Database Fundamentals CHAPTER 2 Exploring Relational Database Components

Java Programming. JDBC Spring Framework Web Services

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

An Introduction to SQL Injection Attacks for Oracle Developers. January 2004 INTEGRIGY. Mission Critical Applications Mission Critical Security

Java SE 7 Programming

Part 2 - The Database Environment

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

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

Oracle SQL Developer for Database Developers. An Oracle White Paper June 2007

Equipment Room Database and Web-Based Inventory Management

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

FileMaker 8. Installing FileMaker 8 ODBC and JDBC Client Drivers

Oracle 10g PL/SQL Training

Intro to Embedded SQL Programming for ILE RPG Developers

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

Oracle to MySQL Migration

Short notes on webpage programming languages

Transcription:

CS/CE 2336 Computer Science II UT D Session 23 Database Programming with Java Adapted from D. Liang s Introduction to Java Programming, 8 th Ed. and other sources 2

Database Recap Application Users Application Programs Database Management System (DBMS) System Users database e.g., Access, MySQL, Oracle, and MS SQL Server 3 Why Java for Database Programming Java is platform independent Platform-independent database applications can be developed using SQL and Java for any relational database systems The support for accessing database systems from Java is built into Java API Database applications using all Java code with a common interface can be easily created Java is ubiquitous Write once, run everywhere Taught in almost every university either as the first programming language or as the second programming language JDBC Java Database Connectivity 4

Pure Java SQL-level interface JDBC Goals Simple yet high performance Leverage existing database technology RDBMS Provide multiple functionalities via multiple methods 5 JDBC Architecture Java Applications/ Applets JDBC API Oracle JDBC Driver JDBC-ODBC Bridge Driver Oracle ODBC Driver Microsoft ODBC Driver Local or remote ORACLE DB Microsoft Access Database ODBC: Open Database Connectivity (1990 s) Applications written in Java invoke JDBC API JDBC loads a driver, connects to a database Can have more than one drivers -> using more than one databases Can change database engines without changing application code! 6

JDBC Interfaces Driver Loading drivers Connection Connection Establishing connections Statement Statement Statement Statement ResultSet ResultSet ResultSet ResultSet Creating and executing statements Processing ResultSet 7 Developing JDBC Programs Loading drivers Establishing connections Creating and executing statements Processing ResultSet Statement to load a driver: Class.forName("JDBCDriverClass"); A driver is a class. For example: Database Driver Class Source Access sun.jdbc.odbc.jdbcodbcdriver Already in JDK MySQL com.mysql.jdbc.driver Website Oracle oracle.jdbc.driver.oracledriver Website The JDBC-ODBC driver for Access is bundled in JDK. MySQL driver class is in mysqljdbc.jar Oracle driver class is in classes12.jar To use the MySQL and Oracle drivers, you have to add mysqljdbc.jar and classes12.jar in the classpath using the following DOS command on Windows: classpath=%classpath%;c:\book\mysqljdbc.jar;c:\book\classes12.jar 8

Developing JDBC Programs Loading drivers Establishing connections Creating and executing statements Processing ResultSet Connection connection = DriverManager.getConnection(databaseURL); Database URL Pattern Access jdbc:odbc:datasource MySQL jdbc:mysql://hostname/dbname Oracle jdbc:oracle:thin:@hostname:port#:oracledbsid Examples: See Supplement IV.D for creating an ODBC data source For Access: Connection connection = DriverManager.getConnection ("jdbc:odbc:examplemdbdatasource"); For MySQL: Connection connection = DriverManager.getConnection ("jdbc:mysql://localhost/test"); For Oracle: Connection connection = DriverManager.getConnection ("jdbc:oracle:thin:@liang.armstrong.edu:1521:orcl", "scott", "tiger"); 9 Developing JDBC Programs Loading drivers Establishing connections Creating and executing statements Processing ResultSet Creating statement: Statement statement = connection.createstatement(); Executing statement (for update, delete, insert): statement.executeupdate ("create table Temp (col1 char(5), col2 char(5))"); Executing statement (for select): // Select the columns from the Student table ResultSet resultset = statement.executequery ("select firstname, mi, lastname from Student where lastname " + " = 'Smith'"); 10

Developing JDBC Programs Loading drivers Establishing connections Creating and executing statements Processing ResultSet Executing statement (for select): // Select the columns from the Student table ResultSet resultset = stmt.executequery ("select firstname, mi, lastname from Student where lastname " + " = 'Smith'"); Processing ResultSet (for select): // Iterate through the result and print the student names while (resultset.next()) System.out.println(resultSet.getString(1) + " " + resultset.getstring(2) + ". " + resultset.getstring(3)); 11 import java.sql.*; public class SimpleJdbc { public static void main(string[] args) throws SQLException, ClassNotFoundException { // Load the JDBC driver Class.forName("com.mysql.jdbc.Driver"); System.out.println("Driver loaded"); // Establish a connection Connection connection = DriverManager.getConnection ("jdbc:mysql://localhost/test"); System.out.println("Database connected"); Simple JDBC Example // Create a statement Statement statement = connection.createstatement(); // Execute a statement ResultSet resultset = statement.executequery ("select firstname, mi, lastname from Student where lastname " + " = 'Smith'"); // Iterate through the result and print the student names while (resultset.next()) System.out.println(resultSet.getString(1) + "\t" + resultset.getstring(2) + "\t" + resultset.getstring(3)); // Close the connection connection.close(); } } 12

Connection Interfaces Once a connection to a particular database is established, SQL statements (e.g. queries) from a program can be sent to the database To facilitate sending statements to a database for execution and receiving execution results from the database JDBC provides following interfaces Statement PreparedStatement CallableStatement 13 Connection Interfaces cont d Statement createstatement() A new Statement object is returned PreparedStatement preparestatement(string sql) Create a new PreparedStatement object CallableStatement preparecall(string sql) Create a new CallableStatement object 14

Processing Statements Diagram 15 PrepareStatement Interface The PreparedStatement interface is designed to execute dynamic SQL statements and SQLstored procedures with IN parameters These SQL statements and stored procedures are precompiled for efficient use when repeatedly executed Statement pstmt = connection.preparestatement ("insert into Student (firstname, mi, lastname) + values (?,?,?)"); 16

Methods for Processing SQL Statements The methods for executing SQL statements are execute, executequery, and executeupdate, Each of these accepts a string containing a SQL statement as an argument The string is passed to the database for execution The execute method should be used if the execution produces multiple result sets, multiple update counts, or a combination of result sets and update counts 17 Methods for Processing SQL Statements cont d The executequery method should be used if the execution produces a single result set, such as the SQL select statement The executeupdate method should be used if the statement results in a single update count or no update count, such as a SQL INSERT, DELETE, UPDATE, or DDL statements 18

Summary of Methods for Processing SQL Statements ResultSet executequery(string) Execute a SQL statement that returns a single ResultSet int executeupdate(string) Execute a SQL statement that returns the number of rows changed INSERT, UPDATE, DELETE or DDL statements boolean execute(string) Execute a SQL statement that may return multiple results 19 ResultSet A ResultSet object provides access to a table resulting from executing a Statement The table rows are retrieved in sequence A ResultSet object maintains a pointer to the current row of data The 'next' method moves the cursor to the next row Only one ResultSet object per Statement can be opened at one time 20

Retrieving Database Metadata Database metadata is the information that describes database itself JDBC provides DatabaseMetaData interface for obtaining database wide information ResultSetMetaData interface for obtaining the information on the specific ResultSet 21 Retrieving Database Metadata The DatabaseMetaData interface provides more than 100 methods for getting database metadata concerning the database as a whole These methods can be divided into three groups for retrieving general information for finding database capabilities, and for getting object descriptions 22

Database Metadata General information The general information includes the URL, username, product name, product version, driver name, driver version, available functions, available data types and so on. Database capabilities The examples of the database capabilities are whether the database supports the GROUP BY operator, the ALTER TABLE command with add column option, supports entrylevel or full ANSI92 SQL grammar. Object descriptions the examples of the database objects are tables, views, and procedures. DatabaseMetaData dbmetadata = connection.getmetadata(); System.out.println("database URL: " + dbmetadata.geturl()); System.out.println("database username: " + dbmetadata.getusername()); System.out.println("database product name: " + dbmetadata.getdatabaseproductname()); System.out.println("database product version: " + dbmetadata.getdatabaseproductversion()); System.out.println("JDBC driver name: " + dbmetadata.getdrivername()); System.out.println("JDBC driver version: " + dbmetadata.getdriverversion()); System.out.println("JDBC driver major version: " + new Integer(dbMetaData.getDriverMajorVersion())); System.out.println("JDBC driver minor version: " + new Integer(dbMetaData.getDriverMinorVersion())); System.out.println("Max number of connections: " + new Integer(dbMetaData.getMaxConnections())); System.out.println("MaxTableNameLentgh: " + new Integer(dbMetaData.getMaxTableNameLength())); System.out.println("MaxColumnsInTable: " + new Integer(dbMetaData.getMaxColumnsInTable())); connection.close(); 23Metadata Example 24