Java Database Connectivity (JDBC) Francisco Pajaro Saul Acosta Nahum Quezada Manuel Rubio.

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

Distributed Application Development B. Ramamurthy.
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
1 Lecture 29 More on JDBC Overview  Objectives of this lecture  JDBC and its Drivers  Connecting to Databases (Java’s Connection class)  Querying a.
EmbeddedSQL: 1 Impedance Mismatch Problem Problem : How to connect SQL statements with conventional programming languages Different models of language.
CSE470 Software Engineering Fall Database Access through Java.
JDBC. In This Class We Will Cover: What SQL is What ODBC is What JDBC is JDBC basics Introduction to advanced JDBC topics.
1 Foundations of Software Design Lecture 27: Java Database Programming Marti Hearst Fall 2002.
Advanced OOP MCS-3 OOP BSCS-3 Lecture # 11. DATABASE CONNECTIVITY IN JAVA JDBC Programming JDBC (Java Database Connectivity) is the specification of a.
Introduction to JDBC (Java Database Connectivity).
CIS 270—App Dev II Big Java Chapter 22 Relational Databases.
Advance Computer Programming Java Database Connectivity (JDBC) – In order to connect a Java application to a database, you need to use a JDBC driver. –
Getting connected.  Java application calls the JDBC library.  JDBC loads a driver which talks to the database.  We can change database engines without.
Java Database Connectivity (JDBC). Introduction Database –Collection of data DBMS –Database management system –Storing and organizing data SQL –Relational.
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.
Advanced Database Management System Lab no. 11. SQL Commands (for MySQL) –Update –Replace –Delete.
Chapter 7 PHP Interacts with Ms. Access (Open DataBase Connectivity (ODBC))
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 8 Object Oriented Programming in Java Advanced Topics Java Database.
Java Database Connectivity Vijayan Sugumaran Department of DIS Oakland University.
Jaeki Song JAVA Lecture 11 Java Database Connectivity.
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.
Database Programming in Java Corresponds with Chapter 32, 33.
Java Utility Classes CS 21b. Some Java Utility Classes Vector Hashtable StringTokenizer * import java.util.*;
CIS 270—Application Development II Chapter 25—Accessing Databases with JDBC.
JDBC (Java Database Connectivity) SNU OOPSLA Lab. October 2005.
Designing and Developing WS B. Ramamurthy. Plans We will examine the resources available for development of JAX-WS based web services. We need an IDE,
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 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.
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. 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.
12/6/2015B.Ramamurthy1 Java Database Connectivity B.Ramamurthy.
Li Tak Sing COMPS311F. Database programming JDBC (Java Database Connectivity) Java version of ODBC (Open Database Connectivity) ODBC provides a standard.
Java and Databases. JDBC Architecture Java Application JDBC API Data Base Drivers AccessSQL Server DB2InformixMySQLSybase.
COMP 321 Week 4. Overview Normalization Entity-Relationship Diagrams SQL JDBC/JDBC Drivers hsqldb Lab 4-1 Introduction.
UNIT III - JDBC JDBC Overview – JDBC implementation – Connection class – Statements - Catching Database Results, handling database Queries. Networking–
DATABASE CONNECTIVITY TO MYSQL. Introduction =>A real life application needs to manipulate data stored in a Database. =>A database is a collection of.
JDBC CS 260 Database Systems. Overview  Introduction  JDBC driver types  Eclipse project setup  Programming with JDBC  Prepared statements  SQL.
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.
Access Databases from Java Programs via JDBC Tessema M. Mengistu Department of Computer Science Southern Illinois University Carbondale
Basics of JDBC Session 14.
JDBC (Java Database Connectivity)
Advanced Java Session 5 New York University School of Continuing and Professional Studies.
Ch. NoNameMarks 01AWT24 02Networking18 03JDBC20 04Swing18 05Servlet20 Advance Java Programming.
Database Programming With Java & JDBC Reading: DD Ch. 18, pp al/jdbc/index.html, or anything covering JDBC.
Introduction to JDBC Instructor: Mohamed Eltabakh 1.
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.
6-1 JAVA DATABASE CONNECTOR Colorado Technical University IT420 Tim Peterson.
CSC 411/511: DBMS Design Dr. Nan WangCSC411_L12_Oracle10g_JDBC 1 Application Development (JDBC)
Java and database. 3 Relational Databases A relational Database consists of a set of simple rectangular tables or relations The column headings are.
DEPTT. OF COMP. SC & APPLICATIONS
Note: To complete the examples in this section you need access to a database!! Most of the examples work for any database with JDBC drivers. However, connecting.
Interacting with Database
Lec - 14.
ODBC, OCCI and JDBC overview
JDBC Database Management Database connectivity
JDBC – ODBC DRIVERS.
Java Database Connectivity
Lecture 11 Database Connection
Java Chapter 6 (Estifanos Tilahun Mihret--Tech with Estif)
Presentation transcript:

Java Database Connectivity (JDBC) Francisco Pajaro Saul Acosta Nahum Quezada Manuel Rubio

Lecture Outline The JDBC API The JDBC Driver Interface The Most Common Use of JDBC Structured Query Language How to Construct SQL Statements The JDBC-ODBC Bridge Register your Database as an ODBC Data Source Things to Do in your Java Program Load the Drivers Make the connection Create JDBC Statements Execute the SQL Statement Retrieve Values from the Result Set

JDBC Introduction JDBC provides a standard library for accessing relational databases API standardizes Way to establish connection to database Approach to initiating queries Method to create stored (parameterized) queries The data structure of query result (table) – Determining the number of columns – Looking up metadata, etc. API does not standardize SQL syntax JDBC is not embedded SQL JDBC classes are in the java.sql package Note: JDBC is not officially an acronym; unofficially, “Java DataBase Connectivity” is commonly used

The JDBC API is expressed as a series of abstract Java interfaces that allow an application programmer to open connections to particular databases, execute SQL statements, and process the results. The most important interfaces are: java.sql.DriverManager which handles loading of drivers and provides support for creating new database connections java.sql.Connection which represents a connection to a particular database java.sql.Statement which acts as a container for executing a SQL statement on a given connection java.sql.ResultSet which controls access to the row results of a given Statement

The JDBC Driver Interface JDBC consists of two parts: – JDBC API, a purely Java-based API – JDBC Driver Manager,which communicates with vendor-specific drivers that perform the real communication with the database. Point: translation to vendor format is performed on the client – No changes needed to server – Driver (translator) needed on client

Application in Java Application in Java DriverManager Sybase drivermSQL driverInformix driver odbc standard API jdbc API

The Most Common Use of JDBC “Perhaps called the Intranet scenario. For example, a company the most common use of these Java applications will be within a company or on an "Intranet," so this might be called the Intranet scenario. For example, a company might implement all of its corporate applications in Java using GUI building tools that generate Java code for forms based on corporate data schemas. These applications would access corporate database servers on a local or wide area network. However, Java applications could also access databases through the Internet.” The JDBC Guide

Structured Query Language SQL KeywordDescription SELECTSelect fields from one or more tables FROMTables from which to get fields WHERECriteria for selection that determine the rows to be retrieved GROUP BYHow to group records HAVINGUsed by the GROUP BY clause to specify criteria for grouping records in the results ORDER BYCriteria for ordering of records

JDBC Data Types

Executing a SELECT query First create a Statement object Then create a query string. For example Execute the query The ResultSet object returned contains the results of the query. Statement stmt = conn.createStatement(); String query = "SELECT * FROM table"; ResultSet rs = stmt.executeQuery(query);

Getting query results (1) Column names and number of columns. If rs is a ResultSet object then number of columns in table is The name of column i ( i =1,2,3,...) is ResultSetMetaData rsmd = rs.getMetaData(); int numberOfColumns = rsmd.getColumnCount(); String colName = rsmd.getColumnName(i)

Getting query results (2) Iterating over the rows of a table while (rs.next()) { for (int i = 1; i <= numberOfColumns; i++) { String columnValue = rs.getString(i); // do something with columnValue } } There are lots of get methods for retriving column values as integers, doubles, etc.

Executing a simple command First create a Statement object Then create a command string. For example Execute the command Statement stmt = conn.createStatement(); String cmd = "DROP TABLE IF EXISTS test"; stmt.execute(cmd);

The JDBC-ODBC Bridge To connect to an MS Access Database you will use JDBC-ODBC bridge, which is included as a standard part of the JDK. You connect using the ODBC Administrator, to connect to the appropriate data source name. Because ODBC has been around for quite a while (longer than the Java language), ODBC drivers are rather ubiquitous. This makes this type of JDBC driver a good choice for learning how to connect Java programs to databases. The extra level of indirection, however, can result in a performance penalty as the JDBC is transferred into ODBC, which is then transferred into the database-specific protocol.

ODBC Client Front-end Application ODBC DB Server Started as a PC-standard. Now it’s an industry standard.

JDBC-ODBC Bridge A layer between the Java front-end application and the database server Client talks to JDBC JDBC communicates with underlying ODBC ODBC communicates with database server Results passed in reverse order to above

Necessary classes Connection: Establishes a connection with the SQL database driver manager Statement: Allows developer to frame fixed SQL queries PreparedStatement: Allows developer to frame SQL queries with parameters ResultSet: Used to collect the results of an SQL query

What is a data source? A data source is a source of data and the connection information needed to access that data. Examples: Microsoft Access Microsoft SQL Server Oracle spreadsheet text file

Examples of connection information: Server location Database name Logon ID password options that describe how to connect to the data source

To connect to these data sources, you must do the following:  Install the appropriate ODBC driver on the computer that contains the data source Microsoft SQL Server Define a data source name (DSN) by using either the ODBC Data Source Administrator spreadsheet

How to register your Database as an ODBC Data Source?  Open up your ODBC Data Sources Administrator.  Click on the System DSN tab and click on the “Add” button.

 The “Create a New Data Source” dialog will appear  Select the driver and click on “Finish”.

 The “ODBC Microsoft Access Setup” dialog will appear.  In the “Data Source Name” box, enter a name. Click the Select Directory button.

 Locate the data base.  Click on “Ok” to exit the dialog.

 And finally, you should now be able to access your data source using ODBC.

Things to Do in your Java Program Load the Drivers Establish the Connection Create JDBC Statement Execute the SQL Statement Retrieve Values from the Result Set

Load the Drivers Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC- ODBC Bridge driver, the following code will load it: Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Query Close Connect Process results Overview of Database Querying with JDBC

Key Classes and Methods in java.sql

Query Close Connect Process results Register the driver Connect to the database Stage 1: Connect

Make the connection  The second step in establishing a connection is to have the appropriate driver connect to the DBMS. The following lines of code illustrates the general idea: String dataSourceName = "mdbTEST"; String dbURL = "jdbc:odbc:" + dataSourceName; Connection con = DriverManager.getConnection (dbURL, "admin","students");

Close Connect Query Create a statement Process results Query the database Stage 2: Query

Create JDBC Statements A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate. It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object stmt : Statement s = con.createStatement( );

Execute the SQL Statement At this point s exists, but it does not have an SQL statement to pass on to the DBMS. We need to supply that to the method we use to execute s. For example, in the following code fragment, we supply executeQuery with the SQL statement from the example above: s.execute("CREATE TABLE Students (ID_Number integer, FirstName VARCHAR(35), LastName VARCHAR(35), VARCHAR(35), University VARCHAR(35))"); ResultSet ResultSet = s.executeQuery(query);

Close Query Step through the results Process results Assign results to Java variables Connect Stage 3: Process the Results

Retrieve Values from the Result Set We now show how you send the SELECT statements from a program written in the Java programming language and how you get the results we showed. JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs and assigning the results of our earlier query to it: String query = "SELECT * FROM Students"; ResultSet ResultSet = s.executeQuery(query);

Inserting/Updating/Deleting Records Statement.executeUpdate Executes an SQL INSERT, UPDATE or DELETE statement.  Parameters: sql - an SQL INSERT, UPDATE or DELETE statement or an SQL statement that returns nothing  Returns: Either the row count for INSERT, UPDATE or DELETE statements, or 0 for SQL statements that return nothing s.execute("INSERT INTO Students VALUES ( , ' Manuel ', ' Rubio ', ' ' UTEP')");

Inserting/Updating/Deleting Records s.execute("UPDATE Students SET FirstName = ' Alonso ' WHERE LastName = 'Rubio '"); s.execute("DELETE FROM Students WHERE LastName = ' Pajaro'")

Connect Query Process results Close Close the result set Close the statement Close the connection Stage 4: Close

1. Close the ResultSet object. 2. Close the Statement object. 3. Close the connection (not necessary for a server-side driver). ResultSet.close(); s.close(); con.close(); How to Close the Connection