SlideShare a Scribd company logo
1 of 65
Java/J2EE Programming Training
JDBC
Page 1Classification: Restricted
Agenda
• Introduction to Databases
• Advantages of Database Systems
• Database Languages
• Distributed Database
• Relational Database Model
• Structured Query Language (SQL)
• Basic Ingredients of JDBC
• Supplying Values for Prepared Statement Parameters
Page 2Classification: Restricted
Introduction to Databases
• File processing
• Random access or sequential
• Only allow access to data
• Cannot query
• Database systems
• Mechanisms to organize and store data
• Allow sophisticated queries
• Relational database - most popular style
• Microsoft Access, Sybase, Oracle
• Structured Query Language (SQL, "sequel")
• Queries relational databases
• Can write Java programs to use SQL queries
Page 3Classification: Restricted
Database Systems
• Database systems
• Cheap, massive, direct access storage available
• Led to research in database systems
• Database - collection of data
• Database system
• Database
• Hardware (where data resides)
• Software
• Database management system (DBMS)
• Controls storage and retrieval
Page 4Classification: Restricted
Advantages of Database Systems
• Advantages
• Reduce redundancy
• Avoid inconsistency
• Share data
• Enforce standards
• Security restrictions
• Data integrity
• Balance conflicting requirements
• Non-database systems
• Each application has own files
• Redundant
• Lack centralized control
Page 5Classification: Restricted
Data Independence
• Data independence
• Applications not dependent on how data stored or accessed
• Data dependency
• Change in storage or retrieval technique forces program change
• Applications can have different views of data
• Change storage/retrieval strategy without changing applications
Page 6Classification: Restricted
Database Languages
• Database language
• Used to access database
• Can use high-level languages
• Java, C, C++, Visual Basic, COBOL, PL/I, Pascal
• Make requests using a specially designed query language
• Host language
• Host languages
• Database sublanguage (DSL) - specifics of database objects and
operations
• Combination of
• Data definition language (DDL) - defines database objects
• Data manipulation language (DML) - specifies processing
• SQL has DDL and DML
Page 7Classification: Restricted
Distributed Database
• Distributed database
• Spread across computers in network
• Data stored where frequently used
• Available to all users
• Advantages
• Control and economics of local processing
• Information access
• Disadvantages
• Costly
• Security risks
Page 8Classification: Restricted
Relational Database Model
• Database models
• Hierarchal, network, relational (most popular)
• Focus on relational
• Relational Database Model
• Logical representation of data
• Consider relationships between data
• Not concerned with implementation
Page 9Classification: Restricted
Relational Database Model
• Relational database
• Composed of tables
• Rows called records
• Columns are fields (attributes)
• First field usually primary key
• Unique for each record
• Primary key can be more than one field (column)
• Primary key not required
Page 10Classification: Restricted
Relational Database Model
Number Name Department Salary Location
23603
24568
35761
34589
47132
78321
JONES, A.
KERWIN, R.
LARSON, P.
MYERS, B.
NEUMANN, C.
STEPHENS, T.
413
413
642
611
413
611
1100
2000
1800
1400
9000
8000
NEW JERSEY
NEW JERSEY
LOS ANGELES
ORLANDO
NEW JERSEY
ORLANDO
Table: Employee
A record
A columnPrimary Key
Page 11Classification: Restricted
Relational Database Model
• Operations
• Projection
• Taking a subset of a table
• Join
• Combining tables to form a larger one
• Example
• Using previous tables, make list of departments and locations
Page 12Classification: Restricted
Relational Database Model
Number Name Department Salary Location
23603
24568
35761
34589
47132
78321
JONES, A.
KERWIN, R.
LARSON, P.
MYERS, B.
NEUMANN, C.
STEPHENS, T.
413
413
642
611
413
611
1100
2000
1800
1400
9000
8000
NEW JERSEY
NEW JERSEY
LOS ANGELES
ORLANDO
NEW JERSEY
ORLANDO
Table: Employee
Department Location
413
642
611
NEW JERSEY
LOS ANGELES
ORLANDO
Projection
(subset)
Page 13Classification: Restricted
Relational Database Model
•Advantages of relational databases
•Tables easy to use, understand, and implement
•Easy to convert other database structures into
relational scheme
• Universal
•Projection and join operations easy to
implement
•Searches faster than schemes with pointers
•Easy to modify - very flexible
•Greater clarity and visibility than other models
SQL
Query
Page 15Classification: Restricted
Select Statement
• keywords
• SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY
Page 16Classification: Restricted
Basic SELECT Query
• SELECT Query
• Selects information from one more tables
• Format
SELECT * FROM TableName
• Asterisk * - select all
• SELECT * FROM Authors
• Selects entire Authors table
• Selecting specific fields
• Replace asterisk (*) with comma separated list
• SELECT AuthorID, LastName FROM Authors
• Ordered left to right
AuthorID LastName
1 Deitel
2 Deitel
3 Nieto
Page 17Classification: Restricted
WHERE Clause
• Selection with criteria
• Only select data that meets requirement
•SELECT * FROM TableName WHERE criteria
• Example
SELECT * FROM Authors WHERE YearBorn > 1960
AuthorID FirstName LastName YearBorn
2 Paul Deitel 1968
3 Tem Nieto 1969
Page 18Classification: Restricted
WHERE Clause
• Conditions
• Can use <, >, <=, >=, =, <> and LIKE
• LIKE - used for pattern matching
• Search for similar strings
• Wildcard characters * and ?
• * - Any number of consecutive characters at asterisk's location
SELECT * FROM Authors WHERE LastName LIKE 'd*'
LastName starts with 'd' followed by any number of characters
AuthorID FirstName LastName YearBorn
1 Harvey Deitel 1946
2 Paul Deitel 1968
Page 19Classification: Restricted
WHERE Clause
• Conditions
• ? - any single character at location
SELECT * FROM Authors WHERE LastName LIKE '?i*'
• LastName begins with any character, 'i' for second character,
followed by any number of charactersAuthorID FirstName LastName YearBorn
3 Tem Nieto 1969
Page 20Classification: Restricted
WHERE Clause
• Conditions
• Range of characters
• [startValue-endValue]
SELECT * FROM Authors WHERE LastName LIKE '?[a-i]*'
• Start with any letter, second letter between a and i, followed by any
number of characters
• All authors fit range
AuthorID FirstName LastName YearBorn
1 Harvey Deitel 1946
2 Paul Deitel 1968
3 Tem Nieto 1969
Page 21Classification: Restricted
ORDER BY Clause
• Arrange results in order
SELECT * FROM TableName ORDER BY field ASC
SELECT * FROM TableName ORDER BY field DESC
• field - field used to order
• ASC/DESC - ascending/descending sort
• ASC default
SELECT * FROM Authors ORDER BY LastName ASC
AuthorID FirstName LastName YearBorn
2 Paul Deitel 1968
1 Harvey Deitel 1946
3 Tem Nieto 1969
Page 22Classification: Restricted
ORDER BY Clause
• Multiple fields
ORDER BY field1 SortingOrder, field2 SortingOrder, ...
• SortingOrder does not have to be same
• If field1 identical for two records, sorts by field2 in order specified
• SELECT * FROM Authors ORDER BY LastName, FirstName
AuthorID FirstName LastName YearBorn
1 Harvey Deitel 1946
2 Paul Deitel 1968
3 Tem Nieto 1969
Page 23Classification: Restricted
ORDER BY Clause
• Combining clauses
• SELECT * FROM Titles
WHERE Title LIKE '*How to Program'
ORDER BY Title ASC
• Multiple lines for readability
ISBN Title
Edition
Number
Year
Published
Publisher
ID
0-13-118043-6 C How to Program 1 1992 1
0-13-226119-7 C How to Program 2 1994 1
0-13-528910-6 C++ How to Program 2 1997 1
0-13-016143-8 Internet and World Wide Web How
to Program
1 1999 1
0-13-012507-5 Java How to Program 3 1999 1
0-13-899394-7 Java How to Program 2 1997 1
0-13-456955-5 Visual Basic 6 How to Program 1 1998 1
Page 24Classification: Restricted
Using INNER JOIN to Merge Data from Multiple Tables
• Merging data
• Combine multiple tables (join) by merging records
• SELECT * FROM Table1 INNER JOIN Table2 ON Table1.field =
Table2.field
• ON - "on condition that"
• Specifies fields to be compared for records to be merged
• Syntax
• If two tables have same field, use TableName.fieldName
• Can be used in any query to distinguish fields
• SELECT FirstName, LastName, ISBN
FROM Authors INNER JOIN AuthorISBN
ON Authors.AuthorID = AuthorISBN.AuthorID
ORDER BY LastName, FirstName
SQL
Update
Page 26Classification: Restricted
SQL to Create a Table
CREATE TABLE Products
(
Product_Code CHAR(11) Description CHAR(40) Unit_Price
DECIMAL(10,2)
)
Page 27Classification: Restricted
SQL to Add Data to a Database
•Use the INSERT command to insert rows into the table
•Issue one command for each row of the table
INSERT INTO Products VALUES ('3554-0632-1', 'Hair dryer', 29.95)
Page 28Classification: Restricted
Inserting and Updating
• SQL statement for inserting data
INSERT INTO tableName ( columnName1, columnName2,... )
VALUES ( 'value1', 'value2', ... )
• Columns to be updated in comma-separated list
• Value for columns specified comma-separated list after VALUES
• Create INSERT INTO statement using JTextFields
109 String query = "INSERT INTO addresses (" +
110 "firstname, lastname, address, city, " +
Page 29Classification: Restricted
Reading, Inserting, and Updating
• Class UpdateRecord
• Event handler for Update button
• UPDATE SQL statement
UPDATE tableName SET columnName1 = 'value1', columnName2 =
'value2', ...
WHERE criteria
• Use ID as criteria
• Use method executeUpdate to update
264 String query = "UPDATE addresses SET " +
265 "firstname='" + fields.first.getText() +
266 "', lastname='" + fields.last.getText() +
267 "', address='" + fields.address.getText() +
Page 30Classification: Restricted
Java Database
Connectivity
Page 31Classification: Restricted
Requirements
Install Java.
Install a DBMS.
Create a database.
Install the JDBC drivers on your machine.
classesxxx.zip
translator.zip (only if using SQLJ)
Page 32Classification: Restricted
Basic Ingredients of JDBC
1.) Declare a database connection object.
2.) Load the JDBC/ODBC Driver class file.
3.) Make a database connection.
4.) Create a statement object.
5.) Execute the statement.
6.) Close the database connection.
Page 33Classification: Restricted
JDBC Driver Types
Driver Type Description
 ODBC-JDBC Bridge Maps JDBC calls to ODBC driver
calls on the client.
 Native API-Java Maps JDBC calls to native calls
on the client.
 JDBC Network-All Java Maps JDBC calls to “network”
protocol, which calls native
methods on server.
 Native Protocol-All Java Directly calls RDBMS from the
client machine.
Page 34Classification: Restricted
JDBC
Loading the JDBC 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");
Your driver documentation will give you the class name to use. For
instance, if the class name is jdbc.DriverXYZ , you would load the driver
with the following line of code:
Class.forName("jdbc.DriverXYZ");
You do not need to create an instance of a driver and register it with the
DriverManager because calling Class.forName will do that for you
automatically.
Page 35Classification: Restricted
Making a Database Connection
It just takes one statemente:
Connection con = DriverManager.getConnection(url,
"myLogin", "myPassword");
This step is also simple, with the hardest thing being what to supply for url .
If you are using the JDBC-ODBC Bridge driver, the JDBC URL will start with
jdbc:odbc: . The rest of the URL is generally your data source name or
database system. So, if you are using ODBC to access an ODBC data source
called " John, " for example, your JDBC URL could be jdbc:odbc:Fred . In
place of " myLogin " you put the name you use to log in to the DBMS; in
place of " myPassword " you put your password for the DBMS. So if you log
in to your DBMS with a login name of " Linda " and a password of " L8, "
just these two lines of code will establish a connection:
String url = "jdbc:odbc:John";
Connection con = DriverManager.getConnection(url, ”Linda", ”L8");
JDBC
Page 36Classification: Restricted
JDBC
Creating JDBC Statements
A Statement object is what sends your SQL statement to the DBMS.
You simply create a Statement object and then execute it
Statement stmt = con.createStatement();
At this point stmt 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 stmt . For example, in the following code fragment, we supply
executeUpdate with the SQL statement from the example above:
stmt.executeUpdate("CREATE TABLE MOVIES " +
"(MOV_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, " +
"SALES INTEGER, TOTAL INTEGER)");
If we made a string out of the SQL statement and assigned it to the
variable createTableMovies , we could have written the code in this
alternate form:
stmt.executeUpdate(createTableCoffees);
Page 37Classification: Restricted
JDBC
Executing Statements
executeUpdate()
executeQuery()
Page 38Classification: Restricted
Basic Ingredients of JDBC
// Declare a database connection object
Connection con = null;
// Load the Driver class file
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Make a connection to the ODBC datasource Movie Catalog
con = DriverManager.getConnection("jdbc:odbc:MovieCatalog",
"", "");
// Create the statement
Statement statement = con.createStatement();
// Use the created statement to SELECT the DATA
// FROM the Titles Table.
ResultSet rs = statement.executeQuery("SELECT * " +
"FROM Titles");
// Close the connection no matter what
con.close();
Page 39Classification: Restricted
JDBC
Result Sets - Metadata & Data
Page 40Classification: Restricted
Basic Ingredients of JDBC
Vector columnHeads = new Vector();
Vector rows = new Vector();
/ get column heads
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println( "rsmd.getColumnCount() " + rsmd.getColumnCount() );
for ( int i = 1; i <= rsmd.getColumnCount(); ++i )
columnHeads.addElement( rsmd.getColumnName( i ) );
// get row data
do {
rows.addElement( getNextRow( rs, rsmd ) );
} while ( rs.next() );
Page 41Classification: Restricted
Basic Ingredients of JDBC
// display table with ResultSet contents
table = new JTable( rows, columnHeads );
JScrollPane scroller = new JScrollPane( table );
getContentPane().add(scroller, BorderLayout.CENTER );
validate();
Page 42Classification: Restricted
JDBC steps
1) Load a Driver
2) Make a Connection
3) Create a Statement
4) Execute a Statement
5) Close the Connection
Page 43Classification: Restricted
Load a Driver
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");
Your driver documentation will give you the class name to use. For instance, if the
class name is jdbc.DriverXYZ , you would load the driver with the following line of
code:
Class.forName("jdbc.DriverXYZ");
You do not need to create an instance of a driver and register it with the
DriverManager because calling Class.forName will do that for you automatically. If
you were to create your own instance, you would be creating an unnecessary
duplicate, but it would do no harm.
When you have loaded a driver, it is available for making a connection with a DBMS.
Page 44Classification: Restricted
Make a Connection
The following line of code illustrates making a connection:
Connection con = DriverManager.getConnection(url,
"myLogin", "myPassword");
If you are using the JDBC-ODBC Bridge driver, the JDBC URL will start with
jdbc:odbc: . The rest of the URL is generally your data source name or
database system. So, if you are using ODBC to access an ODBC data source
called " Fred, " for example, your JDBC URL could be jdbc:odbc:Fred . In place
of " myLogin " you put the name you use to log in to the DBMS; in place of "
myPassword " you put your password for the DBMS. So if you log in to your
DBMS with a login name of " Fernanda " and a password of " J8, " just these
two lines of code will establish a connection:
String url = "jdbc:odbc:Fred";
Connection con = DriverManager.getConnection(url,
"Fernanda", "J8");
Page 45Classification: Restricted
Create a Statement
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 stmt = con.createStatement();
Page 46Classification: Restricted
Execute a Statement
At this point stmt 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 stmt . For
example, in the following code fragment, we supply executeUpdate with the SQL
statement from the example above:
stmt.executeUpdate("CREATE TABLE COFFEES " +
"(COF_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, " +
"SALES INTEGER, TOTAL INTEGER)");
Page 47Classification: Restricted
Closing JDBC Objects
stmt.close();
con.close();
rs.close();
Page 48Classification: Restricted
Retrieving Values from Result Sets
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:
ResultSet rs = stmt.executeQuery( "SELECT * FROM emp“ );
Page 49Classification: Restricted
Using the Method next
The variable rs , which is an instance of ResultSet , contains the selected rows.
In order to access the names and prices, we will go to each row and retrieve the
values according to their types. The method next moves what is called a cursor
to the next row and makes that row (called the current row) the one upon
which we can operate. Since the cursor is initially positioned just above the first
row of a ResultSet object, the first call to the method next moves the cursor to
the first row and makes it the current row. Successive invocations of the method
next move the cursor down one row at a time from top to bottom. The JDBC
2.0 API allows backward movement of the cursor to specific positions and to
positions relative to the current row in addition to moving the cursor forward.
Page 50Classification: Restricted
Using the get Methods
Use the get method of the appropriate type to retrieve the value in each
column. For example, the first column in each row of rs is COF_NAME ,
which stores a value of SQL type VARCHAR . The method for retrieving a
value of SQL type VARCHAR is getString . The second column in each row
stores a value of SQL type FLOAT , and the method for retrieving values
of that type is getFloat . The following code accesses the values stored in
the current row of rs and prints a line with the name followed by three
spaces and the price. Each time the method next is invoked, the next
row becomes the current row, and the loop continues until there are no
more rows in rs .
Page 51Classification: Restricted
Example of Get Method
String query =
"SELECT COF_NAME, PRICE FROM COFFEES";
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
String s = rs.getString("COF_NAME");
float n = rs.getFloat("PRICE");
System.out.println(s + " " + n);
}
Page 52Classification: Restricted
Statement Objects
• Standard
• Prepared
• Callable
Page 53Classification: Restricted
Standard
private String url;
private Connection connect;
url = "jdbc:odbc:AddressBook";
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
connect = DriverManager.getConnection( url );
Statement statement = connect.createStatement();
String query = "SELECT * FROM addresses " +
"WHERE lastname = '";
ResultSet rs = statement.executeQuery( query );
Page 54Classification: Restricted
Prepared
private String url;
private Connection connect;
url = "jdbc:odbc:AddressBook";
Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" );
connect = DriverManager.getConnection( url );
PreparedStatement statement =
connect.PrepareStatement(
"SELECT * FROM addresses ");
ResultSet rs = statement.executeQuery();
Page 55Classification: Restricted
Using Prepared Statements
If you want to execute a Statement object many times, it will normally reduce
execution time to use a PreparedStatement object.
The main feature of a PreparedStatement object is that, unlike a Statement object,
it is given an SQL statement when it is created. The advantage to this is that in most
cases, this SQL statement will be sent to the DBMS right away, where it will be
compiled. As a result, the PreparedStatement object contains not just an SQL
statement, but an SQL statement that has been precompiled. This means that
when the PreparedStatement is executed, the DBMS can just run the
PreparedStatement 's SQL statement without having to compile it first.
Although PreparedStatement objects can be used for SQL statements with no
parameters, you will probably use them most often for SQL statements that take
parameters. The advantage of using SQL statements that take parameters is that
you can use the same statement and supply it with different values each time you
execute it. You will see an example of this in the following sections.
Page 56Classification: Restricted
Creating a PreparedStatement Object
As with Statement objects, you create PreparedStatement objects with a
Connection method. Using our open connection con from previous
examples, you might write code such as the following to create a
PreparedStatement object that takes two input parameters:
PreparedStatement updateSales = con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
The variable updateSales now contains the SQL statement, "UPDATE
COFFEES SET SALES = ? WHERE COF_NAME LIKE ?" , which has also, in most
cases, been sent to the DBMS and been precompiled.
Page 57Classification: Restricted
Supplying Values for Prepared Statement Parameters
Using the PreparedStatement object updateSales from the previous example, the
following line of code sets the first question mark placeholder to a Java int with a
value of 75:
updateSales.setInt(1, 75);
As you might surmise from the example, the first argument given to a setXXX
method indicates which question mark placeholder is to be set, and the second
argument indicates the value to which it is to be set. The next example sets the
second placeholder parameter to the string " Colombian ":
updateSales.setString(2, "Colombian");
Page 58Classification: Restricted
Supplying Values for Prepared Statement Parameters
Page 59Classification: Restricted
Using a Loop to Set Values
Page 60Classification: Restricted
Callable
Original Procedure:
Page 61Classification: Restricted
Callable
Page 62Classification: Restricted
Calling a Stored Procedure from JDBC
Page 63Classification: Restricted
Return Values
executeQuery
executeUpdate
Result Set
Number of Rows
Page 64Classification: Restricted
Thank You

More Related Content

What's hot

Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Jennifer Berk
 
Introduction to XSLT
Introduction to XSLTIntroduction to XSLT
Introduction to XSLTMahmoud Allam
 
Database Essentials for Healthcare Finance Professionals
Database Essentials for Healthcare Finance ProfessionalsDatabase Essentials for Healthcare Finance Professionals
Database Essentials for Healthcare Finance ProfessionalsBrad Adams
 
Dbms oracle
Dbms oracle Dbms oracle
Dbms oracle Abrar ali
 
Basic datatypes - deep understanding
Basic datatypes - deep understandingBasic datatypes - deep understanding
Basic datatypes - deep understandingLiron Amitzi
 
MySQL Index Cookbook
MySQL Index CookbookMySQL Index Cookbook
MySQL Index CookbookMYXPLAIN
 
Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic ConceptsTony Wong
 
Dynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data MergeDynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data MergeClay Helberg
 
Information Retrieval - Data Science Bootcamp
Information Retrieval - Data Science BootcampInformation Retrieval - Data Science Bootcamp
Information Retrieval - Data Science BootcampKais Hassan, PhD
 
Transforming xml with XSLT
Transforming  xml with XSLTTransforming  xml with XSLT
Transforming xml with XSLTMalintha Adikari
 
Sql coding-standard-sqlserver
Sql coding-standard-sqlserverSql coding-standard-sqlserver
Sql coding-standard-sqlserverlochaaaa
 
[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05AnusAhmad
 

What's hot (19)

Xml 2
Xml  2 Xml  2
Xml 2
 
Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)Introduction to SQL (for Chicago Booth MBA technology club)
Introduction to SQL (for Chicago Booth MBA technology club)
 
Basics of XML
Basics of XMLBasics of XML
Basics of XML
 
DB2 Sql Query
DB2 Sql QueryDB2 Sql Query
DB2 Sql Query
 
Introduction to XSLT
Introduction to XSLTIntroduction to XSLT
Introduction to XSLT
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
Database Essentials for Healthcare Finance Professionals
Database Essentials for Healthcare Finance ProfessionalsDatabase Essentials for Healthcare Finance Professionals
Database Essentials for Healthcare Finance Professionals
 
Dbms oracle
Dbms oracle Dbms oracle
Dbms oracle
 
Basic datatypes - deep understanding
Basic datatypes - deep understandingBasic datatypes - deep understanding
Basic datatypes - deep understanding
 
MySQL Index Cookbook
MySQL Index CookbookMySQL Index Cookbook
MySQL Index Cookbook
 
XSLT
XSLTXSLT
XSLT
 
Xslt
XsltXslt
Xslt
 
Database Architecture and Basic Concepts
Database Architecture and Basic ConceptsDatabase Architecture and Basic Concepts
Database Architecture and Basic Concepts
 
Dynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data MergeDynamic Publishing with Arbortext Data Merge
Dynamic Publishing with Arbortext Data Merge
 
Information Retrieval - Data Science Bootcamp
Information Retrieval - Data Science BootcampInformation Retrieval - Data Science Bootcamp
Information Retrieval - Data Science Bootcamp
 
Transforming xml with XSLT
Transforming  xml with XSLTTransforming  xml with XSLT
Transforming xml with XSLT
 
XSLT. Basic.
XSLT. Basic.XSLT. Basic.
XSLT. Basic.
 
Sql coding-standard-sqlserver
Sql coding-standard-sqlserverSql coding-standard-sqlserver
Sql coding-standard-sqlserver
 
[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05[Www.pkbulk.blogspot.com]dbms05
[Www.pkbulk.blogspot.com]dbms05
 

Similar to Java JDBC

xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytWrushabhShirsat3
 
Introduction to DB design
Introduction to DB designIntroduction to DB design
Introduction to DB designVijay Kalangi
 
ADBMS - Joins , Sorting , Distributed Database Systems
ADBMS - Joins , Sorting , Distributed Database SystemsADBMS - Joins , Sorting , Distributed Database Systems
ADBMS - Joins , Sorting , Distributed Database SystemsJoshua Costa
 
Session 1 - Databases-JUNE 2023.pdf
Session 1 - Databases-JUNE 2023.pdfSession 1 - Databases-JUNE 2023.pdf
Session 1 - Databases-JUNE 2023.pdfSwapnilSaurav7
 
•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdfjyothimuppasani1
 
Databases for beginners.pdf
Databases for beginners.pdfDatabases for beginners.pdf
Databases for beginners.pdffikadumola
 
Relational Database Management System
Relational Database Management SystemRelational Database Management System
Relational Database Management SystemMian Abdul Raheem
 
Lec 1 = introduction to structured query language (sql)
Lec 1 = introduction to structured query language (sql)Lec 1 = introduction to structured query language (sql)
Lec 1 = introduction to structured query language (sql)Faisal Anwar
 
Introduction to Structured Query Language (SQL) (1).ppt
Introduction to Structured Query Language (SQL) (1).pptIntroduction to Structured Query Language (SQL) (1).ppt
Introduction to Structured Query Language (SQL) (1).pptComputerScienceDepar6
 
Less07 schema
Less07 schemaLess07 schema
Less07 schemaImran Ali
 
Работа с индексами - лучшие практики для MySQL 5.6, Петр Зайцев (Percona)
Работа с индексами - лучшие практики для MySQL 5.6, Петр Зайцев (Percona)Работа с индексами - лучшие практики для MySQL 5.6, Петр Зайцев (Percona)
Работа с индексами - лучшие практики для MySQL 5.6, Петр Зайцев (Percona)Ontico
 
SQL: Structured Query Language
SQL: Structured Query LanguageSQL: Structured Query Language
SQL: Structured Query LanguageRohit Bisht
 

Similar to Java JDBC (20)

unit-ii.pptx
unit-ii.pptxunit-ii.pptx
unit-ii.pptx
 
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfytxjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
xjtrutdctrd5454drxxresersestryugyufy6rythgfytfyt
 
Introduction to DB design
Introduction to DB designIntroduction to DB design
Introduction to DB design
 
ADBMS - Joins , Sorting , Distributed Database Systems
ADBMS - Joins , Sorting , Distributed Database SystemsADBMS - Joins , Sorting , Distributed Database Systems
ADBMS - Joins , Sorting , Distributed Database Systems
 
Deep Dive on Amazon Redshift
Deep Dive on Amazon RedshiftDeep Dive on Amazon Redshift
Deep Dive on Amazon Redshift
 
Unit - II.pptx
Unit - II.pptxUnit - II.pptx
Unit - II.pptx
 
Session 1 - Databases-JUNE 2023.pdf
Session 1 - Databases-JUNE 2023.pdfSession 1 - Databases-JUNE 2023.pdf
Session 1 - Databases-JUNE 2023.pdf
 
SQL Commands
SQL Commands SQL Commands
SQL Commands
 
•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf•Design (create) 3 questions for a quiz show game and design regular.pdf
•Design (create) 3 questions for a quiz show game and design regular.pdf
 
Databases for beginners.pdf
Databases for beginners.pdfDatabases for beginners.pdf
Databases for beginners.pdf
 
Relational Database Management System
Relational Database Management SystemRelational Database Management System
Relational Database Management System
 
15925 structured query
15925 structured query15925 structured query
15925 structured query
 
Lec 1 = introduction to structured query language (sql)
Lec 1 = introduction to structured query language (sql)Lec 1 = introduction to structured query language (sql)
Lec 1 = introduction to structured query language (sql)
 
Introduction to Structured Query Language (SQL) (1).ppt
Introduction to Structured Query Language (SQL) (1).pptIntroduction to Structured Query Language (SQL) (1).ppt
Introduction to Structured Query Language (SQL) (1).ppt
 
Tunning overview
Tunning overviewTunning overview
Tunning overview
 
Less07 schema
Less07 schemaLess07 schema
Less07 schema
 
Работа с индексами - лучшие практики для MySQL 5.6, Петр Зайцев (Percona)
Работа с индексами - лучшие практики для MySQL 5.6, Петр Зайцев (Percona)Работа с индексами - лучшие практики для MySQL 5.6, Петр Зайцев (Percona)
Работа с индексами - лучшие практики для MySQL 5.6, Петр Зайцев (Percona)
 
IR SQLite Session #1
IR SQLite Session #1IR SQLite Session #1
IR SQLite Session #1
 
Dbms &amp; oracle
Dbms &amp; oracleDbms &amp; oracle
Dbms &amp; oracle
 
SQL: Structured Query Language
SQL: Structured Query LanguageSQL: Structured Query Language
SQL: Structured Query Language
 

More from DeeptiJava

Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesGenerating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesDeeptiJava
 
Java Collection
Java CollectionJava Collection
Java CollectionDeeptiJava
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception HandlingDeeptiJava
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access SpecifierDeeptiJava
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner ClassDeeptiJava
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate BasicsDeeptiJava
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to JavaDeeptiJava
 

More from DeeptiJava (13)

Generating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status CodesGenerating the Server Response: HTTP Status Codes
Generating the Server Response: HTTP Status Codes
 
Java Generics
Java GenericsJava Generics
Java Generics
 
Java Collection
Java CollectionJava Collection
Java Collection
 
Java Exception Handling
Java Exception HandlingJava Exception Handling
Java Exception Handling
 
Java OOPs
Java OOPs Java OOPs
Java OOPs
 
Java Access Specifier
Java Access SpecifierJava Access Specifier
Java Access Specifier
 
Java Thread
Java ThreadJava Thread
Java Thread
 
Java Inner Class
Java Inner ClassJava Inner Class
Java Inner Class
 
JSP Part 2
JSP Part 2JSP Part 2
JSP Part 2
 
JSP Part 1
JSP Part 1JSP Part 1
JSP Part 1
 
Java I/O
Java I/OJava I/O
Java I/O
 
Java Hibernate Basics
Java Hibernate BasicsJava Hibernate Basics
Java Hibernate Basics
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 

Recently uploaded

Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 

Recently uploaded (20)

Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 

Java JDBC

  • 2. Page 1Classification: Restricted Agenda • Introduction to Databases • Advantages of Database Systems • Database Languages • Distributed Database • Relational Database Model • Structured Query Language (SQL) • Basic Ingredients of JDBC • Supplying Values for Prepared Statement Parameters
  • 3. Page 2Classification: Restricted Introduction to Databases • File processing • Random access or sequential • Only allow access to data • Cannot query • Database systems • Mechanisms to organize and store data • Allow sophisticated queries • Relational database - most popular style • Microsoft Access, Sybase, Oracle • Structured Query Language (SQL, "sequel") • Queries relational databases • Can write Java programs to use SQL queries
  • 4. Page 3Classification: Restricted Database Systems • Database systems • Cheap, massive, direct access storage available • Led to research in database systems • Database - collection of data • Database system • Database • Hardware (where data resides) • Software • Database management system (DBMS) • Controls storage and retrieval
  • 5. Page 4Classification: Restricted Advantages of Database Systems • Advantages • Reduce redundancy • Avoid inconsistency • Share data • Enforce standards • Security restrictions • Data integrity • Balance conflicting requirements • Non-database systems • Each application has own files • Redundant • Lack centralized control
  • 6. Page 5Classification: Restricted Data Independence • Data independence • Applications not dependent on how data stored or accessed • Data dependency • Change in storage or retrieval technique forces program change • Applications can have different views of data • Change storage/retrieval strategy without changing applications
  • 7. Page 6Classification: Restricted Database Languages • Database language • Used to access database • Can use high-level languages • Java, C, C++, Visual Basic, COBOL, PL/I, Pascal • Make requests using a specially designed query language • Host language • Host languages • Database sublanguage (DSL) - specifics of database objects and operations • Combination of • Data definition language (DDL) - defines database objects • Data manipulation language (DML) - specifies processing • SQL has DDL and DML
  • 8. Page 7Classification: Restricted Distributed Database • Distributed database • Spread across computers in network • Data stored where frequently used • Available to all users • Advantages • Control and economics of local processing • Information access • Disadvantages • Costly • Security risks
  • 9. Page 8Classification: Restricted Relational Database Model • Database models • Hierarchal, network, relational (most popular) • Focus on relational • Relational Database Model • Logical representation of data • Consider relationships between data • Not concerned with implementation
  • 10. Page 9Classification: Restricted Relational Database Model • Relational database • Composed of tables • Rows called records • Columns are fields (attributes) • First field usually primary key • Unique for each record • Primary key can be more than one field (column) • Primary key not required
  • 11. Page 10Classification: Restricted Relational Database Model Number Name Department Salary Location 23603 24568 35761 34589 47132 78321 JONES, A. KERWIN, R. LARSON, P. MYERS, B. NEUMANN, C. STEPHENS, T. 413 413 642 611 413 611 1100 2000 1800 1400 9000 8000 NEW JERSEY NEW JERSEY LOS ANGELES ORLANDO NEW JERSEY ORLANDO Table: Employee A record A columnPrimary Key
  • 12. Page 11Classification: Restricted Relational Database Model • Operations • Projection • Taking a subset of a table • Join • Combining tables to form a larger one • Example • Using previous tables, make list of departments and locations
  • 13. Page 12Classification: Restricted Relational Database Model Number Name Department Salary Location 23603 24568 35761 34589 47132 78321 JONES, A. KERWIN, R. LARSON, P. MYERS, B. NEUMANN, C. STEPHENS, T. 413 413 642 611 413 611 1100 2000 1800 1400 9000 8000 NEW JERSEY NEW JERSEY LOS ANGELES ORLANDO NEW JERSEY ORLANDO Table: Employee Department Location 413 642 611 NEW JERSEY LOS ANGELES ORLANDO Projection (subset)
  • 14. Page 13Classification: Restricted Relational Database Model •Advantages of relational databases •Tables easy to use, understand, and implement •Easy to convert other database structures into relational scheme • Universal •Projection and join operations easy to implement •Searches faster than schemes with pointers •Easy to modify - very flexible •Greater clarity and visibility than other models
  • 16. Page 15Classification: Restricted Select Statement • keywords • SELECT, FROM, WHERE, GROUP BY, HAVING, ORDER BY
  • 17. Page 16Classification: Restricted Basic SELECT Query • SELECT Query • Selects information from one more tables • Format SELECT * FROM TableName • Asterisk * - select all • SELECT * FROM Authors • Selects entire Authors table • Selecting specific fields • Replace asterisk (*) with comma separated list • SELECT AuthorID, LastName FROM Authors • Ordered left to right AuthorID LastName 1 Deitel 2 Deitel 3 Nieto
  • 18. Page 17Classification: Restricted WHERE Clause • Selection with criteria • Only select data that meets requirement •SELECT * FROM TableName WHERE criteria • Example SELECT * FROM Authors WHERE YearBorn > 1960 AuthorID FirstName LastName YearBorn 2 Paul Deitel 1968 3 Tem Nieto 1969
  • 19. Page 18Classification: Restricted WHERE Clause • Conditions • Can use <, >, <=, >=, =, <> and LIKE • LIKE - used for pattern matching • Search for similar strings • Wildcard characters * and ? • * - Any number of consecutive characters at asterisk's location SELECT * FROM Authors WHERE LastName LIKE 'd*' LastName starts with 'd' followed by any number of characters AuthorID FirstName LastName YearBorn 1 Harvey Deitel 1946 2 Paul Deitel 1968
  • 20. Page 19Classification: Restricted WHERE Clause • Conditions • ? - any single character at location SELECT * FROM Authors WHERE LastName LIKE '?i*' • LastName begins with any character, 'i' for second character, followed by any number of charactersAuthorID FirstName LastName YearBorn 3 Tem Nieto 1969
  • 21. Page 20Classification: Restricted WHERE Clause • Conditions • Range of characters • [startValue-endValue] SELECT * FROM Authors WHERE LastName LIKE '?[a-i]*' • Start with any letter, second letter between a and i, followed by any number of characters • All authors fit range AuthorID FirstName LastName YearBorn 1 Harvey Deitel 1946 2 Paul Deitel 1968 3 Tem Nieto 1969
  • 22. Page 21Classification: Restricted ORDER BY Clause • Arrange results in order SELECT * FROM TableName ORDER BY field ASC SELECT * FROM TableName ORDER BY field DESC • field - field used to order • ASC/DESC - ascending/descending sort • ASC default SELECT * FROM Authors ORDER BY LastName ASC AuthorID FirstName LastName YearBorn 2 Paul Deitel 1968 1 Harvey Deitel 1946 3 Tem Nieto 1969
  • 23. Page 22Classification: Restricted ORDER BY Clause • Multiple fields ORDER BY field1 SortingOrder, field2 SortingOrder, ... • SortingOrder does not have to be same • If field1 identical for two records, sorts by field2 in order specified • SELECT * FROM Authors ORDER BY LastName, FirstName AuthorID FirstName LastName YearBorn 1 Harvey Deitel 1946 2 Paul Deitel 1968 3 Tem Nieto 1969
  • 24. Page 23Classification: Restricted ORDER BY Clause • Combining clauses • SELECT * FROM Titles WHERE Title LIKE '*How to Program' ORDER BY Title ASC • Multiple lines for readability ISBN Title Edition Number Year Published Publisher ID 0-13-118043-6 C How to Program 1 1992 1 0-13-226119-7 C How to Program 2 1994 1 0-13-528910-6 C++ How to Program 2 1997 1 0-13-016143-8 Internet and World Wide Web How to Program 1 1999 1 0-13-012507-5 Java How to Program 3 1999 1 0-13-899394-7 Java How to Program 2 1997 1 0-13-456955-5 Visual Basic 6 How to Program 1 1998 1
  • 25. Page 24Classification: Restricted Using INNER JOIN to Merge Data from Multiple Tables • Merging data • Combine multiple tables (join) by merging records • SELECT * FROM Table1 INNER JOIN Table2 ON Table1.field = Table2.field • ON - "on condition that" • Specifies fields to be compared for records to be merged • Syntax • If two tables have same field, use TableName.fieldName • Can be used in any query to distinguish fields • SELECT FirstName, LastName, ISBN FROM Authors INNER JOIN AuthorISBN ON Authors.AuthorID = AuthorISBN.AuthorID ORDER BY LastName, FirstName
  • 27. Page 26Classification: Restricted SQL to Create a Table CREATE TABLE Products ( Product_Code CHAR(11) Description CHAR(40) Unit_Price DECIMAL(10,2) )
  • 28. Page 27Classification: Restricted SQL to Add Data to a Database •Use the INSERT command to insert rows into the table •Issue one command for each row of the table INSERT INTO Products VALUES ('3554-0632-1', 'Hair dryer', 29.95)
  • 29. Page 28Classification: Restricted Inserting and Updating • SQL statement for inserting data INSERT INTO tableName ( columnName1, columnName2,... ) VALUES ( 'value1', 'value2', ... ) • Columns to be updated in comma-separated list • Value for columns specified comma-separated list after VALUES • Create INSERT INTO statement using JTextFields 109 String query = "INSERT INTO addresses (" + 110 "firstname, lastname, address, city, " +
  • 30. Page 29Classification: Restricted Reading, Inserting, and Updating • Class UpdateRecord • Event handler for Update button • UPDATE SQL statement UPDATE tableName SET columnName1 = 'value1', columnName2 = 'value2', ... WHERE criteria • Use ID as criteria • Use method executeUpdate to update 264 String query = "UPDATE addresses SET " + 265 "firstname='" + fields.first.getText() + 266 "', lastname='" + fields.last.getText() + 267 "', address='" + fields.address.getText() +
  • 31. Page 30Classification: Restricted Java Database Connectivity
  • 32. Page 31Classification: Restricted Requirements Install Java. Install a DBMS. Create a database. Install the JDBC drivers on your machine. classesxxx.zip translator.zip (only if using SQLJ)
  • 33. Page 32Classification: Restricted Basic Ingredients of JDBC 1.) Declare a database connection object. 2.) Load the JDBC/ODBC Driver class file. 3.) Make a database connection. 4.) Create a statement object. 5.) Execute the statement. 6.) Close the database connection.
  • 34. Page 33Classification: Restricted JDBC Driver Types Driver Type Description  ODBC-JDBC Bridge Maps JDBC calls to ODBC driver calls on the client.  Native API-Java Maps JDBC calls to native calls on the client.  JDBC Network-All Java Maps JDBC calls to “network” protocol, which calls native methods on server.  Native Protocol-All Java Directly calls RDBMS from the client machine.
  • 35. Page 34Classification: Restricted JDBC Loading the JDBC 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"); Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ , you would load the driver with the following line of code: Class.forName("jdbc.DriverXYZ"); You do not need to create an instance of a driver and register it with the DriverManager because calling Class.forName will do that for you automatically.
  • 36. Page 35Classification: Restricted Making a Database Connection It just takes one statemente: Connection con = DriverManager.getConnection(url, "myLogin", "myPassword"); This step is also simple, with the hardest thing being what to supply for url . If you are using the JDBC-ODBC Bridge driver, the JDBC URL will start with jdbc:odbc: . The rest of the URL is generally your data source name or database system. So, if you are using ODBC to access an ODBC data source called " John, " for example, your JDBC URL could be jdbc:odbc:Fred . In place of " myLogin " you put the name you use to log in to the DBMS; in place of " myPassword " you put your password for the DBMS. So if you log in to your DBMS with a login name of " Linda " and a password of " L8, " just these two lines of code will establish a connection: String url = "jdbc:odbc:John"; Connection con = DriverManager.getConnection(url, ”Linda", ”L8"); JDBC
  • 37. Page 36Classification: Restricted JDBC Creating JDBC Statements A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it Statement stmt = con.createStatement(); At this point stmt 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 stmt . For example, in the following code fragment, we supply executeUpdate with the SQL statement from the example above: stmt.executeUpdate("CREATE TABLE MOVIES " + "(MOV_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, " + "SALES INTEGER, TOTAL INTEGER)"); If we made a string out of the SQL statement and assigned it to the variable createTableMovies , we could have written the code in this alternate form: stmt.executeUpdate(createTableCoffees);
  • 38. Page 37Classification: Restricted JDBC Executing Statements executeUpdate() executeQuery()
  • 39. Page 38Classification: Restricted Basic Ingredients of JDBC // Declare a database connection object Connection con = null; // Load the Driver class file Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); // Make a connection to the ODBC datasource Movie Catalog con = DriverManager.getConnection("jdbc:odbc:MovieCatalog", "", ""); // Create the statement Statement statement = con.createStatement(); // Use the created statement to SELECT the DATA // FROM the Titles Table. ResultSet rs = statement.executeQuery("SELECT * " + "FROM Titles"); // Close the connection no matter what con.close();
  • 41. Page 40Classification: Restricted Basic Ingredients of JDBC Vector columnHeads = new Vector(); Vector rows = new Vector(); / get column heads ResultSetMetaData rsmd = rs.getMetaData(); System.out.println( "rsmd.getColumnCount() " + rsmd.getColumnCount() ); for ( int i = 1; i <= rsmd.getColumnCount(); ++i ) columnHeads.addElement( rsmd.getColumnName( i ) ); // get row data do { rows.addElement( getNextRow( rs, rsmd ) ); } while ( rs.next() );
  • 42. Page 41Classification: Restricted Basic Ingredients of JDBC // display table with ResultSet contents table = new JTable( rows, columnHeads ); JScrollPane scroller = new JScrollPane( table ); getContentPane().add(scroller, BorderLayout.CENTER ); validate();
  • 43. Page 42Classification: Restricted JDBC steps 1) Load a Driver 2) Make a Connection 3) Create a Statement 4) Execute a Statement 5) Close the Connection
  • 44. Page 43Classification: Restricted Load a Driver 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"); Your driver documentation will give you the class name to use. For instance, if the class name is jdbc.DriverXYZ , you would load the driver with the following line of code: Class.forName("jdbc.DriverXYZ"); You do not need to create an instance of a driver and register it with the DriverManager because calling Class.forName will do that for you automatically. If you were to create your own instance, you would be creating an unnecessary duplicate, but it would do no harm. When you have loaded a driver, it is available for making a connection with a DBMS.
  • 45. Page 44Classification: Restricted Make a Connection The following line of code illustrates making a connection: Connection con = DriverManager.getConnection(url, "myLogin", "myPassword"); If you are using the JDBC-ODBC Bridge driver, the JDBC URL will start with jdbc:odbc: . The rest of the URL is generally your data source name or database system. So, if you are using ODBC to access an ODBC data source called " Fred, " for example, your JDBC URL could be jdbc:odbc:Fred . In place of " myLogin " you put the name you use to log in to the DBMS; in place of " myPassword " you put your password for the DBMS. So if you log in to your DBMS with a login name of " Fernanda " and a password of " J8, " just these two lines of code will establish a connection: String url = "jdbc:odbc:Fred"; Connection con = DriverManager.getConnection(url, "Fernanda", "J8");
  • 46. Page 45Classification: Restricted Create a Statement 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 stmt = con.createStatement();
  • 47. Page 46Classification: Restricted Execute a Statement At this point stmt 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 stmt . For example, in the following code fragment, we supply executeUpdate with the SQL statement from the example above: stmt.executeUpdate("CREATE TABLE COFFEES " + "(COF_NAME VARCHAR(32), SUP_ID INTEGER, PRICE FLOAT, " + "SALES INTEGER, TOTAL INTEGER)");
  • 48. Page 47Classification: Restricted Closing JDBC Objects stmt.close(); con.close(); rs.close();
  • 49. Page 48Classification: Restricted Retrieving Values from Result Sets 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: ResultSet rs = stmt.executeQuery( "SELECT * FROM emp“ );
  • 50. Page 49Classification: Restricted Using the Method next The variable rs , which is an instance of ResultSet , contains the selected rows. In order to access the names and prices, we will go to each row and retrieve the values according to their types. The method next moves what is called a cursor to the next row and makes that row (called the current row) the one upon which we can operate. Since the cursor is initially positioned just above the first row of a ResultSet object, the first call to the method next moves the cursor to the first row and makes it the current row. Successive invocations of the method next move the cursor down one row at a time from top to bottom. The JDBC 2.0 API allows backward movement of the cursor to specific positions and to positions relative to the current row in addition to moving the cursor forward.
  • 51. Page 50Classification: Restricted Using the get Methods Use the get method of the appropriate type to retrieve the value in each column. For example, the first column in each row of rs is COF_NAME , which stores a value of SQL type VARCHAR . The method for retrieving a value of SQL type VARCHAR is getString . The second column in each row stores a value of SQL type FLOAT , and the method for retrieving values of that type is getFloat . The following code accesses the values stored in the current row of rs and prints a line with the name followed by three spaces and the price. Each time the method next is invoked, the next row becomes the current row, and the loop continues until there are no more rows in rs .
  • 52. Page 51Classification: Restricted Example of Get Method String query = "SELECT COF_NAME, PRICE FROM COFFEES"; ResultSet rs = stmt.executeQuery(query); while (rs.next()) { String s = rs.getString("COF_NAME"); float n = rs.getFloat("PRICE"); System.out.println(s + " " + n); }
  • 53. Page 52Classification: Restricted Statement Objects • Standard • Prepared • Callable
  • 54. Page 53Classification: Restricted Standard private String url; private Connection connect; url = "jdbc:odbc:AddressBook"; Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ); connect = DriverManager.getConnection( url ); Statement statement = connect.createStatement(); String query = "SELECT * FROM addresses " + "WHERE lastname = '"; ResultSet rs = statement.executeQuery( query );
  • 55. Page 54Classification: Restricted Prepared private String url; private Connection connect; url = "jdbc:odbc:AddressBook"; Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver" ); connect = DriverManager.getConnection( url ); PreparedStatement statement = connect.PrepareStatement( "SELECT * FROM addresses "); ResultSet rs = statement.executeQuery();
  • 56. Page 55Classification: Restricted Using Prepared Statements If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object. The main feature of a PreparedStatement object is that, unlike a Statement object, it is given an SQL statement when it is created. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's SQL statement without having to compile it first. Although PreparedStatement objects can be used for SQL statements with no parameters, you will probably use them most often for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it. You will see an example of this in the following sections.
  • 57. Page 56Classification: Restricted Creating a PreparedStatement Object As with Statement objects, you create PreparedStatement objects with a Connection method. Using our open connection con from previous examples, you might write code such as the following to create a PreparedStatement object that takes two input parameters: PreparedStatement updateSales = con.prepareStatement( "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?"); The variable updateSales now contains the SQL statement, "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?" , which has also, in most cases, been sent to the DBMS and been precompiled.
  • 58. Page 57Classification: Restricted Supplying Values for Prepared Statement Parameters Using the PreparedStatement object updateSales from the previous example, the following line of code sets the first question mark placeholder to a Java int with a value of 75: updateSales.setInt(1, 75); As you might surmise from the example, the first argument given to a setXXX method indicates which question mark placeholder is to be set, and the second argument indicates the value to which it is to be set. The next example sets the second placeholder parameter to the string " Colombian ": updateSales.setString(2, "Colombian");
  • 59. Page 58Classification: Restricted Supplying Values for Prepared Statement Parameters
  • 63. Page 62Classification: Restricted Calling a Stored Procedure from JDBC
  • 64. Page 63Classification: Restricted Return Values executeQuery executeUpdate Result Set Number of Rows