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

Post on 26-Dec-2015

214 Views

Category:

Documents

1 Downloads

Preview:

Click to see full reader

Transcript

Java Database Connectivity (JDBC)

Francisco PajaroSaul AcostaNahum 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” iscommonly 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 withvendor-specific drivers thatperform the real communicationwith the database.• Point: translation to vendor

format is performed onthe client– No changes neededto server– Driver (translator) neededon client

Application in Java

Application inJava

DriverManager

Sybase driver mSQL driver Informix driver

odbc stan

dard 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 Keyword Description

SELECT Select fields from one or more tables

FROM Tables from which to get fields

WHERE Criteria for selection that determine the rows to be retrieved

GROUP BY How to group records

HAVING Used by the GROUP BY clause to specify criteria for grouping records in the results

ORDER BY Criteria 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 asintegers, 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 DBServer

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

Processresults

Overview of Database Querying with JDBC

DriverManager

getConnection()

Connection

createStatement()

Statement

executeQuery()

ResultSet

getMetaData()next()getString()

ResultSetMetaData

getColumnCount()

Key Classes and Methods in java.sql

Query

Close

Connect

Processresults

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

Processresults

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),

EMail VARCHAR(35),

University VARCHAR(35))");

ResultSet ResultSet = s.executeQuery(query);

Close

QueryStep through the results

Processresults

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 (890124532 , ' Manuel ', ' Rubio ', ' marubio@utep.edu', ' 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

Processresults

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

top related