Basics of JDBC.

Slides:



Advertisements
Similar presentations
Java Database Connectivity (JDBC). 2/24 JDBC (Java DataBase Connectivity) - provides access to relational database systems JDBC is a vendor independent.
Advertisements

Database programming in Java An introduction to Java Database Connectivity (JDBC)
JDBC. Java Database Connectivity (JDBC) Use the java.sql package to query and update the database. JDBC is an API that allows java to communicate with.
JDBC - Java Database Connectivity The objectives of this chapter are: To describe the architecture of JDBC To outline the classes in the java.sql package.
15-Jun-15 JDBC. JDBC is a Sun trademark It is often taken to stand for Java Database Connectivity Java is very standardized, but there are many versions.
1 C. Shahabi Application Programming for Relational Databases Cyrus Shahabi Computer Science Department University of Southern California
Object-Oriented Enterprise Application Development Introduction to JDBC.
1 Lecture 29 More on JDBC Overview  Objectives of this lecture  JDBC and its Drivers  Connecting to Databases (Java’s Connection class)  Querying a.
Lab: JDBC 1 Computer Engineering Lab III v Objective –to give some background on JDBC to help with the lab exercises , Semester 1,
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
1 Java Database Connection (JDBC) There are many industrial-strength DBMS's commercially available in the market. Oracle, DB2, and Sybase are just a few.
Helena Pomezná, ciz034 St. skupina: L392 FEI, VŠB-TUO Ak. rok. 2002/2003 Download:
CS178 Database Management “JDBC”. What is JDBC ? JDBC stands for “Java DataBase Connectivity” The standard interface for communication between a Java.
Java Database Connectivity Vijayan Sugumaran Department of DIS Oakland University.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java/jsp program to connect to any database.
© Wang Bin 2004 JDBC ----Java Database Connectivity.
CSE470 Software Engineering Fall Database Access through Java.
Beginning Databases with JDBC Mike Bradley Adapted from and notes by Kevin Parker, Ph.D.
Java Database Connectivity (JDBC) Introduction to JDBC JDBC is a simple API for connecting from Java applications to multiple databases. Lets you smoothly.
Java Database Connectivity ASE. Java Database Connectivity (JDBC) l JDBC – provides an interface to Relational Data Sources l JDBC library provides the.
Database Programming in Java Corresponds with Chapter 32, 33.
MySQL, Java, and JDBC CSE 3330 Southern Methodist University.
JDBC Tutorial MIE456 - Information Systems Infrastructure II Vinod Muthusamy November 4, 2004.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
JAVA Database Access. JDBC The Java Database Connectivity (JDBC) API is the industry standard for database- independent connectivity between the Java.
CS 405G: Introduction to Database Systems Database programming.
Connecting to Oracle using Java November 4, 2009 David Goldschmidt, Ph.D. David Goldschmidt, Ph.D.
Computer Engineering Lab
JDBC. JDBC stands for Java Data Base Connectivity. JDBC is different from ODBC in that – JDBC is written in Java (hence is platform independent, object.
JDBC  The JDBC (Java Database Connectivity) API helps a Java program to access a database in a standard way  JDBC is a specification that tells the.
Sadegh Aliakbary. Copyright ©2014 JAVACUP.IRJAVACUP.IR All rights reserved. Redistribution of JAVACUP contents is not prohibited if JAVACUP.
JDBC Enterprise Systems Programming. JDBC  Java Database Connectivity  Database Access Interface provides access to a relational database (by allowing.
Accessing Database using JDBC. JDBC Objectives Gain basic knowledge of Java JDBC Become familiar with the basics of interacting with a database using.
COMP201 Java Programming Topic 15: Database Connectivity JDBC Reading: Chapter 4, Volume 2.
WEB/DB1 DATABASE PROGRAMMING 3JDBC by the ASU Scholars.
JDBC – Java Database Concentricity
Chapter 25 Databases. Chapter Scope Database concepts Tables and queries SQL statements Managing data in a database Java Foundations, 3rd Edition, Lewis/DePasquale/Chase25.
Java Database Connectivity (JDBC). Topics 1. The Vendor Variation Problem 2. SQL and Versions of JDBC 3. Creating an ODBC Data Source 4. Simple Database.
JDBC Database Programming in Java Prepared by., Mrs.S.Amudha AP/SWE.
JDBC. Java.sql.package The java.sql package contains various interfaces and classes used by the JDBC API. This collection of interfaces and classes enable.
JDBC CS 124. JDBC Java Database Connectivity Database Access Interface provides access to a relational database (by allowing SQL statements to be sent.
Session 30 Basics of JDBC. Java Simplified / Session 30 / 2 of 33 Review A Swing menu consists of a menubar, menuitems and menus. Trees are used to depict.
Java and Databases. JDBC Architecture Java Application JDBC API Data Base Drivers AccessSQL Server DB2InformixMySQLSybase.
DATABASE CONNECTIVITY TO MYSQL. Introduction =>A real life application needs to manipulate data stored in a Database. =>A database is a collection of.
EXAMPLE I An application showing JDBC access to Cloudscape.
CSI 3125, Preliminaries, page 1 JDBC. CSI 3125, Preliminaries, page 2 JDBC JDBC stands for Java Database Connectivity, which is a standard Java API (application.
JDBC (Java Database Connectivity)
JDBC - Java Database Connectivity. JDBC provides Java applications with access to most database systems via SQL The architecture and API closely resemble.
Introduction to JDBC Instructor: Mohamed Eltabakh 1.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 Java Database Connectivity.
In the Name Of Almighty Allah. Java Application Connection To Mysql Created by Hasibullah (Sahibzada) Kabul Computer Science Faculty Afghanistan.
Intro to JDBC Joseph Sant Applied Computing and Engineering Sciences Sheridan ITAL.
JDBC. What is JDBC JDBC is an acronym for –Java Data Base Connectivity. It allows java program to connect to any database.
CS320 Web and Internet Programming Database Access with JDBC Chengyu Sun California State University, Los Angeles.
CS3220 Web and Internet Programming Database Access with JDBC
Interacting with Database
JDBC 15-Apr-18.
Database JDBC Overview CS Programming Languages for Web Applications
Advanced Web Automation Using Selenium
JDBC 21-Aug-18.
HW#4 Making Simple BBS Using JDBC
Introduction to Programming with Java
JDBC 15-Nov-18.
Objectives In this lesson, you will learn about:
Interacting with Database
JDBC Example.
CS3220 Web and Internet Programming Database Access with JDBC
CS3220 Web and Internet Programming Database Access with JDBC
Presentation transcript:

Basics of JDBC

Overview What is JDBC? Why need an application other than DBMS? How JDBC can help? JDBC Steps Transactions in JDBC JDBC Drivers Summary

What is JDBC? JDBC is: a Sun trademark is often taken to stand for Java Database Connectivity. is a Java API for connecting programs written in Java to the data in relational databases. consists of a set of classes and interfaces written in the Java programming language. provides a standard API for tool/database developers and makes it possible to write database applications using a pure Java API. The standard defined by Sun Microsystems, allowing individual providers to implement and extend the standard with their own JDBC drivers. JDBC is the standard for portable access to relational databases from within the Java language. JDBC is based on the X/Open SQL Call Level Interface, and complies with the SQL92 Entry Level standard. JDBC specifies a set of object-orient programming classes for the programmer to use in building SQL requests. An additional set of classes describes the JDBC driver API. The most common SQL data types, mapped to Java data types, are supported. The API provides for implementation-specific support for transactional requests and the ability to commit or roll back to the beginning of a transaction.

JDBC Java is very standardized, but there are many versions of SQL JDBC is a means of accessing SQL databases from Java JDBC is a standardized API for use by Java programs JDBC is also a specification for how third-party vendors should write database drivers to access specific SQL versions JDBC: establishes a connection with a database sends SQL statements processes the results.

The need of an application Databases offer structured storing, easy retrieval and processing of data The maintenance, however, can be tedious Suppose you manage a database store on an SQL server. Then you need to have a knowledge on SQL in order to retrieve or update data. This will not be that pleasant for you. Will it? An application in between can do the job for you The application will deal with the database while you interact with the user-friendly GUI

JDBC Java Database Connectivity Provides a Java API to access SQL databases

The JDBC API The JDBC API contains methods to communicate with DBMS or RDBMS The JDBC API uses the JDBC driver to carry out it tasks The JDBC API & Driver enables a Java application to: 1. Establish a connection with a data source 2. Send queries and update statements to the data source 3. Process the results Java Program JDBC API JDBC Driver Database The process of accessing the database

JDBC API The JDBC API supports both two-tier and three-tier models for database access. Two-tier model -- a Java applet or application interacts directly with the database. Three-tier model -- introduces a middle-level server for execution of business logic: the middle tier to maintain control over data access. the user can employ an easy-to-use higher-level API which is translated by the middle tier into the appropriate low-level calls.

The JDBC API The JDBC API supports both two-tier and three-tier models Java applet or HTML browser Client machine (GUI) Java Application HTTP, RMI, CORBA or other calls Client machine JDBC Application server (Java) Server machine (business logic) DBMS – proprietary protocol JDBC Database server DBMS – proprietary protocol DBMS Database server DBMS Two-tier model Three-tier model

JDBC Classes java.sql. DriverManager Connection Statement ResultSet getConnection Connection createStatement Statement execute, executeQuery, executeBatch, executeUpdate ResultSet next, getString, getInt, getDate, getMetaData ResultSetMetadata getColumnCount, getColumnName, getColumnType

JDBC Steps Instantiate proper driver 2. Open connection to database 3. Connect to database 4. Query database (or insert/update/delete) 5. Process the result 6. Close connection to database

1. Instantiate Driver Class.forName(“driver class”) Driver class is vendor dependent, e.g., sun.jdbc.odbc.JdbcOdbcDriver JDBC-ODBC bridge used to access ODBC Sources com.mysql.jdbc.Driver driver to access MySQL database com.sybase.jdbc2.jdbc.SybDriver driver to access Sybase database

2. Open Connection jdbc:mysql://localhost:3306/testDB DriverManager.getConnection(url) or DriverManager.getConnection(url, user, pwd) return Connection URL is jdbc:<subprotocol>:<subname> e.g., jdbc:odbc:someDB jdbc:<subprotocol>://<host>:<port>/<db> jdbc:mysql://localhost:3306/testDB

3. Connect to database Load JDBC driver Make connection URL Class.forName("com.mysql.jdbc.Driver").newInstance(); Make connection Connection conn = DriverManager.getConnection(url); URL Format: jdbc:<subprotocol>://<host>:<port>/<db> jdbc:mysql://localhost:3306/testDB

4. Query database Create statement Send SQL statements Statement stmt = conn.createStatement(); stmt object sends SQL commands to database Methods executeQuery() for SELECT statements executeUpdate() for INSERT, UPDATE, DELETE, statements Send SQL statements stmt.executeQuery(“SELECT …”); stmt.executeUpdate(“INSERT …”);

5. Process results users table Result of a SELECT statement (rows/columns) returned as a ResultSet object ResultSet rs = stmt.executeQuery("SELECT * FROM users"); Step through each row in the result rs.next() Get column values in a row String userid = rs.getString(“userid”); int type = rs.getInt(“type”); users table userid firstname lastname password type Bob King cat John Smith pass 1

Print the users table users table ResultSet rs = stmt.executeQuery("SELECT * FROM users"); while (rs.next()) { String userid = rs.getString(1); String firstname = rs.getString(“firstname”); String lastname = rs.getString(“lastname”); String password = rs.getString(4); int type = rs.getInt(“type”); System.out.println(userid + ” ” + firstname + ” ” + lastname + ” ” + password + ” ” + type); } users table userid firstname lastname password type Bob King cat John Smith pass 1

Add a row to the users table String str = "INSERT INTO users VALUES('Bob', 'Bob', 'King', 'cat', 0)”; //Returns number of rows in table int rows = stmt.executeUpdate(str); users table userid firstname lastname password type Bob King cat

6. Closing connections Close the ResultSet object rs.close(); Close the Statement object stmt.close(); Close the connection conn.close();

import java.sql.*; public class Tester { public static void main(String[] args) { try { // Load JDBC driver Class.forName("com.mysql.jdbc.Driver"); // Make connection String url = “jdbc:mysql://localhost:3306/testDB”; Connection conn = DriverManager.getConnection(url, ”root”, ”rev”); // Create statement Statement stmt = conn.createStatement(); // Print the users table ResultSet rs = stmt.executeQuery("SELECT * FROM users"); while (rs.next()) { ... } // Cleanup rs.close(); stmt.close(); conn.close(); catch (Exception e) { System.out.println("exception " + e);

Transactions Currently every executeUpdate() is “finalized” right away Sometimes want to a set of updates to all fail or all succeed E.g. add to Appointments and Bookings tables Treat both inserts as one transaction Transaction Used to group several SQL statements together Either all succeed or all fail

Transactions Commit Rollback Execute all statements as one unit “Finalize” updates Rollback Abort transaction All uncommited statements are discarded Revert database to original state

Transactions in JDBC Disable auto-commit for the connection conn.setAutoCommit(false); Call necessary executeUpdate() statements Commit or rollback conn.commit(); conn.rollback();

JDBC Driver There are four flavors of JDBC JDBC-ODBC Bridge (Type 1 driver) Native-API/partly-Java driver (Type 2 driver) Net-protocol/all-Java driver (Type 3 driver) Native-protocol/all-Java driver (Type 4 driver)

Native-protocol/all-Java driver JDBC Driver We will use the, Native-protocol/all-Java driver Java Application Native-protocol/all-Java driver Database server Functionality of Type 4 driver

On The Job Required software Java-2 JVM s including JDK – 1.4x or newer to compile MySQL server version 4.1 or newer MySQL Connector/J Note: We have used MySQL as the database server and MySQL Connector/J as the database specific JDBC driver

Example import java.sql.*; import java.io.*; class JDBC { public static void main(String[] args) try Connection conn; Statement stmt; String Query; ResultSet rs; Class.forName("com.mysql.jdbc.Driver"); conn=DriverManager.getConnection("jdbc:mysql://localhost/game","root","password"); stmt=conn.createStatement();

Query="select * from table1"; rs=stmt.executeQuery(Query); while(rs.next()) { String s = rs.getString(1); System.out.println(s); } rs.close(); conn.close(); catch(SQLException sqle) { System.out.println(sqle); catch(Exception e) System.out.println(e);

Loading the Driver a) Import statements import java.sql.*; b) Loading the database driver Class.forName("com.mysql.jdbc.Driver"); - We load the driver class by calling Class.forName() with the Driver class name as an argument - If the class name is jdbc.DriverXYZ , you would load the driver with the following line of code: Class.forName("jdbc.DriverXYZ"); - Once loaded, the Driver class creates an instance of itself.