Java Database Connectivity (JDBC) 25.1 What is JDBC?

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

About the Tutorial. Audience. Prerequisites. Copyright & Disclaimer

Preview from Notesale.co.uk Page 21 of 162

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

Unit 3 - Java Data Base Connectivity

C:/Users/zzaier/Documents/NetBeansProjects/WebApplication4/src/java/mainpackage/MainClass.java

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal

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

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

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

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

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

UNIT-3 Java Database Client/Server

Java. Curs 2. Danciu Gabriel Mihail. Septembrie 2018

Accessing databases in Java using JDBC

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

Java Database Connectivity

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

SQL in a Server Environment

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

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

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

Java Database Connectivity

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

Cập nhật ResultSet trong JDBC

1. PhP Project. Create a new PhP Project as shown below and click next

Databases 2012 Embedded SQL

SQream Connector JDBC SQream Technologies Version 2.9.3

Databases and JDBC. by Vlad Costel Ungureanu for Learn Stuff

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

Programming in Java

Chapter 10 Java and SQL. Wang Yang

JDBC, Transactions. Niklas Fors JDBC 1 / 38

Database Application Development

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

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

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

Web Applications and Database Connectivity using JDBC (Part II)

Visit for more.

Logging and Recovery. 444 Section, April 23, 2009

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

Application Programming for Relational Databases

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

Databases and SQL Lab EECS 448

SQL-PL Interface. Murali Mani. Perl /CGI with Oracle/mySQL Install your own web server and use servlets with JDBC and Oracle/mySQL

CSE 135. Three-Tier Architecture. Applications Utilizing Databases. Browser. App. Server. Database. Server

Introduction to Databases

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

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

Lab # 9. Java to Database Connection

SQL and Java. Database Systems Lecture 20 Natasha Alechina

DB I. 1 Dr. Ahmed ElShafee, Java course

Working with Databases and Java

Unit 2 JDBC Programming

INTRODUCTION TO JDBC - Revised spring

Three-Tier Architecture

Accessing a database from Java. Using JDBC

COMP102: Introduction to Databases, 23

DB Programming. Database Systems

What is Transaction? Why Transaction Management Required? JDBC Transaction Management in Java with Example. JDBC Transaction Management Example

Lab 6-1: MySQL Server

INTRODUCTION TO JDBC - Revised Spring

Chapter 1 An introduction to relational databases and SQL

Enterprise Systems. Lecture 02: JDBC. Behzad BORDBAR

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

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

DATABASE DESIGN I - 1DL300

PESIT Bangalore South Campus

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

JDBC Java Database Connectivity is a Java feature that lets you connect

Servlet 5.1 JDBC 5.2 JDBC

Vendor: IBM. Exam Code: Exam Name: DB2 9 Application Developer. Version: Demo

Oracle Database 10g Java Web

IBM DB2 9 Application Developer. Download Full Version :

Oracle Exam 1z0-809 Java SE 8 Programmer II Version: 6.0 [ Total Questions: 128 ]

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

13 Creation and Manipulation of Tables and Databases

VanillaCore Walkthrough Part 1. Introduction to Database Systems DataLab CS, NTHU

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

UNIT III - JDBC Two Marks

Database Explorer Quickstart

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

Tutorial: Using Java/JSP to Write a Web API

Copyright 2012, Oracle and/or its affiliates. All rights reserved.

Tiers (or layers) Separation of concerns

Departamento de Lenguajes y Sistemas Informáticos

Chapter 16: Databases

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

Intoduction to JDBC (Java Database Connectivity-- Connecting to DBMS)

SNS COLLEGE OF ENGINEERING, Coimbatore

EMBEDDED SQL. SE 3DB3 Fall 2016 MICHAEL LIUT DEPARTMENT OF COMPUTING AND SOFTWARE MCMASTER UNIVERSITY

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

SMS Service. Type Source Remarks Common? Service interface for the SMS Service. egovframework.com.cop.sms.service.egovsmsinfoservice.

Java Database Connectivity

CHAPTER 44. Java Stored Procedures

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

Wentworth Institute of Technology COMP570 Database Applications Fall 2014 Derbinsky. SQL Programming. Lecture 8. SQL Programming

JDBC Overview. Java Database Connectivity. Gregg Lippa Senior Technical Analyst Themis Education Themis, Inc.

Database connectivity (II)

Persistency Patterns. Repository and DAO

Transcription:

PART 25 Java Database Connectivity (JDBC) 25.1 What is JDBC? JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases. The JDBC library includes APIs for each of the tasks commonly associated with database usage: Making a connection to a database Creating SQL or MySQL statements Executing that SQL or MySQL queries in the database Viewing & Modifying the resulting records 25.2 JDBC Architecture The JDBC Architecture consists of two layers: JDBC API: This provides the application-to-jdbc Manager connection. JDBC Driver API: This supports the JDBC Manager-to-Driver Connection. Following is the architectural diagram, which shows the location of the driver manager with respect to the JDBC drivers and the Java application:

25.3 Common JDBC Components The JDBC API provides the following interfaces and classes: DriverManager: This class manages a list of database drivers. Driver: This interface handles the communications with the database server. You will interact directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages objects of this type. Connection : This interface with all methods for contacting a database. Statement : You use objects created from this interface to submit the SQL statements to the database. ResultSet: These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data. SQLException: This class handles any errors that occur in a database application. 25.6 Install Database Install a database that is most suitable for you. You can have plenty of choices and most common are:

MySQL DB: MySQL is an open source database. You can download it from MySQL Official Site. We recommend downloading the full Windows installation. In addition, download and install MySQL Administrator as well as MySQL Query Browser. These are GUI based tools that will make your development much easier. Finally, download and unzip MySQL Connector/J (the MySQL JDBC driver) in a convenient directory. PostgreSQL DB: PostgreSQL is an open source database. You can download it frompostgresql Official Site. The Postgres installation contains a GUI based administrative tool called pgadmin III. JDBC drivers are also included as part of the installation. Oracle DB: Oracle DB is an commercial database. Oracle installation includes a GUI based administrative tool called Enterprise Manager. JDBC drivers are also included as part of the installation. 25.7 Set up MySQL Database For this tutorial we are going to use MySQL database. When you install any of the above database, its administrator ID is set to root and gives provision to set a password of your choice. Using root ID and password you can either create another users ID and password or you can use root ID and password for your JDBC application. There are various database operations like database creation and deletion, which would need administrator ID and password. 25.7.1 Create Database To create the EMP database, use the following steps: Step 1: Open a Command Prompt and change to the installation directory as follows:

C:\> C:\>cd Program Files\MySQL\bin C:\Program Files\MySQL\bin> Note: The path to mysqld.exe may vary depending on the install location of MySQL on your system. Step 2: Start the database server by executing the following command, if it is already not running. C:\Program Files\MySQL\bin>mysqld C:\Program Files\MySQL\bin> Step 3: Create the EMP database by executing the following command C:\Program Files\MySQL\bin> mysqladmin create EMP -u root -p Enter password: ******** C:\Program Files\MySQL\bin> 25.7.2 Create Table To create the Employees table in EMP database, use the following steps: Step 1: Open a Command Prompt and change to the installation directory as follows: C:\> C:\>cd Program Files\MySQL\bin C:\Program Files\MySQL\bin> Step 2: Login to database as follows C:\Program Files\MySQL\bin>mysql -u root -p Enter password: ******** mysql>

Step 3: Create the table Employee as follows: mysql> use EMP; mysql> create table Employees -> ( -> id int not null, -> age int not null, -> first varchar (255), -> last varchar (255) -> ); Query OK, 0 rows affected (0.08 sec) mysql> 25.7.3 Create Data Records Finally you create few records in Employee table as follows: mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali'); Query OK, 1 row affected (0.05 sec) mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan'); Query OK, 1 row affected (0.00 sec) mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal'); Query OK, 1 row affected (0.00 sec) mysql> Now you are ready to start experimenting with JDBC. Next tutorial would give your a sample example on JDBC Programming. 25.8 Creating JDBC Application (SELECT) First, download the MySQL JDBC connector from mysql web site: http://dev.mysql.com/downloads/connector/j/ Download and unzip files, you will find mysql-connector-java-5.1.24-bin.jar file. You need to add mysql-connector-java-5.1.24-bin.jar file in your CLASSPATH (In Eclipse drag and drop into src folder, right click mysql-connector-java-5.1.24-bin.jar and select Build Path-> Add to Build Path)

There are following six steps involved in building a JDBC application: Import the packages. Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. Register the JDBC driver: Requires that you initialize a driver so you can open a communications channel with the database. Open a connection: Requires the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database. Execute a query: Requires using an object of type Statement for building and submitting an SQL statement to the database. Extract data from result set: Once SQL query is executed, you can fetch records from the table. Clean up the environment: Requires explicitly closing all database resources. This sample example can serve as a template when you need to create your own JDBC application in the future. //STEP 1. Import required packages import java.sql.*; public class FirstExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.driver"; static final String DB_URL = "jdbc:mysql://localhost/emp"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(string[] args) { Connection conn = null; Statement stmt = null; //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createstatement(); String sql;

sql = "SELECT id, first, last, age FROM Employees"; ResultSet rs = stmt.executequery(sql); //STEP 5: Extract data from result set while(rs.next()){ //Retrieve by column name int id = rs.getint("id"); int age = rs.getint("age"); String first = rs.getstring("first"); String last = rs.getstring("last"); //Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } //STEP 6: Clean-up environment rs.close(); stmt.close(); //Handle errors for JDBC }catch(exception e){ //Handle errors for Class.forName e.printstacktrace(); }finally{ //finally block used to close resources if(stmt!=null) stmt.close(); }catch(sqlexception se2){ }// nothing we can do if(conn!=null) }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end FirstExample When you run FirstExample, it produces following result: C:\>java FirstExample Connecting to database... Creating statement... ID: 100, Age: 18, First: Zara, Last: Ali ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal C:\>

25.9 Creating JDBC Application (INSERT) This tutorial provides an example on how to insert records in a table using JDBC application. There are following steps required to create a new JDBC INSERT application: Import the packages Register the JDBC driver Open a connection Execute a query Clean up the environment //STEP 1. Import required packages import java.sql.*; public class JDBCExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.driver"; static final String DB_URL = "jdbc:mysql://localhost/emp"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(string[] args) { Connection conn = null; Statement stmt = null; //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); //STEP 4: Execute a query System.out.println("Inserting records into the table..."); stmt = conn.createstatement(); String sql = "INSERT INTO Employees VALUES (104, 18,'Ahmet', 'Yildiz')"; stmt.executeupdate(sql); sql = "INSERT INTO Employees VALUES (105,25,'Zuhal', 'Ak')"; stmt.executeupdate(sql); sql = "INSERT INTO Employees VALUES (106,30,'Mert', 'Akin')"; stmt.executeupdate(sql); sql = "INSERT INTO Employees VALUES(107,28,'Selim', 'Man')"; stmt.executeupdate(sql); System.out.println("Inserted records into the table..."); //Handle errors for JDBC }catch(exception e){ //Handle errors for Class.forName e.printstacktrace(); }finally{

//finally block used to close resources if(stmt!=null) }// do nothing if(conn!=null) }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end JDBCExample When you run JDBCExample, it produces following result: C:\>java JDBCExample Connecting to a selected database... Connected database successfully... Inserting records into the table... Inserted records into the table... Goodbye! C:\> 25.10 Creating JDBC Application (UPDATE) There are following steps required to create a JDBC UPDATE application: Import the packages Register the JDBC driver Open a connection Execute a query Clean up the environment //STEP 1. Import required packages import java.sql.*; public class JDBCupdate { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.driver"; static final String DB_URL = "jdbc:mysql://localhost/emp"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(string[] args) { Connection conn = null; Statement stmt = null; //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createstatement(); String sql = "UPDATE Employees SET age = 30 WHERE id in (100, 101)"; stmt.executeupdate(sql); // Now you can extract all the records // to see the updated records sql = "SELECT id, first, last, age FROM Employees"; ResultSet rs = stmt.executequery(sql); while(rs.next()){ //Retrieve by column name int id = rs.getint("id"); int age = rs.getint("age"); String first = rs.getstring("first"); String last = rs.getstring("last"); //Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } rs.close(); //Handle errors for JDBC }catch(exception e){ //Handle errors for Class.forName e.printstacktrace(); }finally{ //finally block used to close resources if(stmt!=null) }// do nothing if(conn!=null) }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end JDBCupdate When you run JDBCupdate, it produces following result: C:\>java JDBCupdate Connecting to a selected database... Connected database successfully... Creating statement... ID: 100, Age: 30, First: Zara, Last: Ali ID: 101, Age: 30, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal

Goodbye! C:\> 25.11 Creating JDBC Application (DELETE) There are following steps required to create a JDBC DELETE application: Import the packages Register the JDBC driver Open a connection Execute a query Clean up the environment //STEP 1. Import required packages import java.sql.*; public class JDBCdelete { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.driver"; static final String DB_URL = "jdbc:mysql://localhost/emp"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(string[] args) { Connection conn = null; Statement stmt = null; //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createstatement(); String sql = "DELETE FROM Employees WHERE id = 101"; stmt.executeupdate(sql); // Now you can extract all the records // to see the remaining records sql = "SELECT id, first, last, age FROM Employees"; ResultSet rs = stmt.executequery(sql); while(rs.next()){ //Retrieve by column name int id = rs.getint("id"); int age = rs.getint("age"); String first = rs.getstring("first"); String last = rs.getstring("last"); //Display values System.out.print("ID: " + id); System.out.print(", Age: " + age);

System.out.print(", First: " + first); System.out.println(", Last: " + last); } rs.close(); //Handle errors for JDBC }catch(exception e){ //Handle errors for Class.forName e.printstacktrace(); }finally{ //finally block used to close resources if(stmt!=null) }// do nothing if(conn!=null) }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end JDBCdelete When you run JDBCdelete, it produces following result: C:\>java JDBCdelete Connecting to a selected database... Connected database successfully... Creating statement... ID: 100, Age: 30, First: Zara, Last: Ali ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal Goodbye! C:\> 25.12 PreparedStatement Object The PreparedStatement interface extends the Statement interface which gives you added functionality with a couple of advantages over a generic Statement object. This statement gives you the flexibility of supplying arguments dynamically.

//STEP 1. Import required packages import java.sql.*; public class JDBCdelete { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.driver"; static final String DB_URL = "jdbc:mysql://localhost/emp"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(string[] args) { Connection conn = null; PreparedStatement pstmt = null; try { // STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); // STEP 3: Open a connection System.out.println("Connecting to a selected database..."); conn = DriverManager.getConnection(DB_URL, USER, PASS); System.out.println("Connected database successfully..."); // STEP 4: Execute a query System.out.println("Inserting record into the table..."); String sql = "INSERT INTO ogrenci VALUES (?,?,?,?)"; pstmt = conn.preparestatement(sql); pstmt.setint(1, 112); pstmt.setint(2, 32); pstmt.setstring(3, "Halil"); pstmt.setstring(4, "Guven"); pstmt.executeupdate(); System.out.println("Inserted record into the table..."); } catch (SQLException se) { // Handle errors for JDBC } catch (Exception e) { // Handle errors for Class.forName e.printstacktrace(); } finally { // finally block used to close resources try { if (pstmt!= null) } catch (SQLException se) { }// do nothing try { if (conn!= null) } catch (SQLException se) { }// end finally try }// end try System.out.println("Goodbye!"); }// end main }// end JDBCprepared

All parameters in JDBC are represented by the? symbol, which is known as the parameter marker. You must supply values for every parameter before executing the SQL statement. The setxxx() methods bind values to the parameters, where XXX represents the Java data type of the value you wish to bind to the input parameter. If you forget to supply the values, you will receive an SQLException. Each parameter marker is referred to by its ordinal position. The first marker represents position 1, the next position 2, and so forth. This method differs from that of Java array indices, which start at 0. All of the Statement object's methods for interacting with the database (a) execute(), (b) executequery(), and (c) executeupdate() also work with the PreparedStatement object.