0% found this document useful (0 votes)
9 views

7-jdbc-with-notes-for-2024

Uploaded by

Mehedi Hasan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

7-jdbc-with-notes-for-2024

Uploaded by

Mehedi Hasan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

lOMoARcPSD|50347845

7-JDBC-with Notes for 2024

Computer Science (University of Cape Town)

Scan to open on Studocu

Studocu is not sponsored or endorsed by any college or university


Downloaded by X Gaming (xmehedi1210@gmail.com)
lOMoARcPSD|50347845

Embedded
SQL and
JDBC

Downloaded by X Gaming (xmehedi1210@gmail.com)


lOMoARcPSD|50347845

Why Embedded SQL?

• For complex queries and applications

• Gives the capabilities of both SQL and a high


level language like C++ or Java.

Downloaded by X Gaming (xmehedi1210@gmail.com)


lOMoARcPSD|50347845

Prerequisites
(these must all be installed – already
installed for mysql on nightmare here)

• A DBMS
• Java and JDBC ( JDBC API )
• Drivers

Downloaded by X Gaming (xmehedi1210@gmail.com)


lOMoARcPSD|50347845

JDBC
• JDBC is a set of Java interfaces
– Driver, Connection, Statement, ResultSet, etc.
• Database vendors (companies selling a DBMS
e.g. Oracle) implement these interfaces

• If we switch from one DBMS to another, we


just load a different driver (plug and play) and
don’t need to change the rest of the code

Downloaded by X Gaming (xmehedi1210@gmail.com)


lOMoARcPSD|50347845

Terminology

• Embedded SQL
– SQL statements inside a host program i.e. inside a
program written in a host language like Java or C++
• JDBC
– A Java API for connecting to databases. Defines
behaviour
• JDBC Driver
– An implementation of the JDBC driver interface
provided by a database vendor like Oracle etc.
• Database URL
– A string to uniquely determine a database server and
database

Downloaded by X Gaming (xmehedi1210@gmail.com)


lOMoARcPSD|50347845

Overview of programming with JDBC

• Import JDBC classes


– import java.sql.*
• Load a driver
• Make a connection
• Interact with the Database
– Create JDBC Statements
– Execute JDBC Statements
– Process JDBC ResultSet
• Close the connection

Downloaded by X Gaming (xmehedi1210@gmail.com)


lOMoARcPSD|50347845

JDBC

DriverManager Connection Statement ResultSet

This shows the 4 main types Driver


of action commonly used with
JDBC. There are a great many
others not covered here, that
are well documented online –
e.g. to fetch metadata to get Database
details about the tables and
their columns, etc.
Downloaded by X Gaming (xmehedi1210@gmail.com)
lOMoARcPSD|50347845

JDBC

DriverManager Connection Statement ResultSet

Driver

import java.sql.*;
static String DRIVER =
“com.mysql.jdbc.Driver”;
Class.forName ( DRIVER ); Database

Downloaded by X Gaming (xmehedi1210@gmail.com)


lOMoARcPSD|50347845

Making a Connection
import java.sql.*;
Connection conn= DriverManager.getConnection
("jdbc:oracle:thin:@server.cs.uct.ac.za:1521:CS01",
loginname, passwd);

the URL for the database includes the protocol (Jdbc), the vendor
(Oracle), the driver (thin), the server (server.cs.uct.ac.za), the
port number (1521) and a server instance (CS01).
URL is followed by database username and password

To more easily make changes, use initialized variables instead:


DriverManager.getConnection(URL, USERNAME, PASSWORD);

Downloaded by X Gaming (xmehedi1210@gmail.com)


lOMoARcPSD|50347845

Creating JDBC Statement

A JDBC statement object :

is associated with an open connection

is like a channel on the connection for passing


statements to the DBMS

no SQL is specified or executed yet

• Statement stmt = conn.createStatement ();

Downloaded by X Gaming (xmehedi1210@gmail.com)


lOMoARcPSD|50347845

Creating a statement
Statement st = conn.createStatement( ); // example 1

Statement st =conn.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE ); // example 2

TYPE_SCROLL_SENSITIVE means result tuples will not only be


processed in order (see e.g. myResultSet.previous() etc
later). If left out this defaults to TYPE_FORWARD_ONLY
CONCUR_UPDATABLE means the result set can be updated – if
left out this defaults to CONCUR_READ_ONLY i.e. no
database changes can then be made

Downloaded by X Gaming (xmehedi1210@gmail.com)


lOMoARcPSD|50347845

• ResultSet objects hold the results of a query. They have a cursor.

• TYPE_FORWARD_ONLY: The result set cannot be scrolled; its cursor


moves forward only, from before the first row to after the last row. It
contains the rows that satisfy the query at either the time the query is
executed or as the rows are retrieved. This is the default.
• TYPE_SCROLL_INSENSITIVE: The cursor can move forward and
backward, and to an absolute position. The result set is insensitive to
changes made to the underlying data source while it is open. It
contains the rows that satisfy the query at either the time the query is
executed or as the rows are retrieved.
• TYPE_SCROLL_SENSITIVE: The cursor can move both forward and
backward, and to an absolute position. The result set reflects changes
made to the underlying data source while the result set remains open.

• CONCUR_READ_ONLY: The ResultSet object cannot be updated using


the ResultSet interface.
• CONCUR_UPDATABLE: The ResultSet object can be updated using
the ResultSet interface

• Note: Not all databases and JDBC drivers support all ResultSet types.
Downloaded by X Gaming (xmehedi1210@gmail.com)
lOMoARcPSD|50347845

Executing
• You create a string that is standard SQL syntax
and pass it to the Statement object

• Execute an update

String SQL = "INSERT INTO rel VALUES (44)";


st.executeUpdate(SQL);

• Execute a query and create a ResultSet

String SQL = "SELECT snum FROM suppliers";


ResultSet rec = st.executeQuery(SQL);
Downloaded by X Gaming (xmehedi1210@gmail.com)
lOMoARcPSD|50347845

executeUpdate( ) Statement

These change the state of the database, e.g.

stmt.executeUpdate (“Create table Member “ +


“(Member_Id number(4 ) primary key, ” +
“Member_Name Varchar2(15))”);

stmt.executeUpdate("insert into Member values” +


“(12, ‘Jim Hu’ )");

Downloaded by X Gaming (xmehedi1210@gmail.com)


lOMoARcPSD|50347845

Using ResultSet to print all tuples of a relation

String query = "select * from Passing";

ResultSet rs = stmt.executeQuery(query);

while ( rs.next( ) ) {
String ID = rs.getString(“ID");
String name = rs.getString("NAME");
int marks = rs.getInt("MARKS");
System.out.println(ID+”,”+name+”:”+marks)
}
19
Downloaded by X Gaming (xmehedi1210@gmail.com)
lOMoARcPSD|50347845

Extract attributes of interest from each tuple by


giving the column name or column number

while( rs.next( ) )
{ System.out.println( rs.getString(“ID") );
}
// or
while( rs.next( ) )
{ System.out.println( rs.getString(1) );
// first column of the resultset
}
fini
Downloaded by X Gaming (xmehedi1210@gmail.com)
lOMoARcPSD|50347845

Example of executeQuery( )

ResultSet rs;
rs = stmt.executeQuery (“select * from Member”);
while ( rs.next ( ) )
{
int memID= rs.getInt (1);
String mName = rs.getString (2);
System.out.println (“Member Id:” + memID +
“Member Name:”+ mName);
}
Downloaded by X Gaming (xmehedi1210@gmail.com)
lOMoARcPSD|50347845

Scrollable Result Set



Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);

String query = “select students from class where type=‘not sleeping’ “;


ResultSet rs = stmt.executeQuery( query );

rs.previous(); / / go back to previous tuple in the ResultSet


rs.relative(-5); / / go back 5 tuples
rs.relative(7); / / go forward 7 tuples
rs.absolute(10); / / go to 10th tuple of ResultSet

22
Downloaded by X Gaming (xmehedi1210@gmail.com)
lOMoARcPSD|50347845

Updatable ResultSet

Statement stmt =
con.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
String query = " select students, grade from class
where type=‘attending’ “;
ResultSet rs = stmt.executeQuery( query );

while ( rs.next() )
{
int grade = rs.getInt(“grade”);
rs.updateInt(“grade”, grade+10);
rs.updateRow();
}

23
Downloaded by X Gaming (xmehedi1210@gmail.com)
lOMoARcPSD|50347845

Use prepared statement to optimize your code


PreparedStatement p = conn.prepareStatement(
"SELECT * FROM Users WHERE city = ? and suburb = ?” );
// some loop structure here
{ // begin loop
- - -
p.setString(1,cityname);
p.setString(2,burbname);
burbname);

ResultSet rs = sp.executeQuery();
- - - Should just be p
ANALYZE TABLE T; This helps to analyse the table
} // end loop EXPLAIN SELECT Will show you diff plans that exist and how expensive they are

prepareStatement causes the SQL command in the given string to be analysed


and the most efficient plan for executing that SQL to be determined and
compiled ready for execution.
This is thus done just once before the loop, and that execution plan is then
reused each time the loop runs. Instead of just running multiple times at each loop 35
Downloaded by X Gaming (xmehedi1210@gmail.com)
lOMoARcPSD|50347845

DriverManager Connection Statement ResultSet

Driver
import java.sql.*;
static String DRIVER =
“com.mysql.jdbc.Driver”; Database
Class.forName ( DRIVER );
Connection conn = DriverManager.getConnection (
"jdbc:oracle:thin:@server.cs.uct.ac.za:1521:CS01",login,passwd);

Statement stm = conn.createStatement( );


ResultSet res = stm.executeQuery(“Select * from orders”);

while (res.next() )
{ myFunc (res.getString(1), res.getInt(2), res.getString(3) );
}
Downloaded by X Gaming (xmehedi1210@gmail.com)
lOMoARcPSD|50347845

Close up to free resources

• stmt.close();
• con.close();

25
Downloaded by X Gaming (xmehedi1210@gmail.com)
lOMoARcPSD|50347845

Example

27

Downloaded by X Gaming (xmehedi1210@gmail.com)


lOMoARcPSD|50347845

Example

28

Downloaded by X Gaming (xmehedi1210@gmail.com)


lOMoARcPSD|50347845

Example

29

Downloaded by X Gaming (xmehedi1210@gmail.com)


lOMoARcPSD|50347845

catch (SQLException se)


{
se.printStackTrace();
}
finally {
try {
if (conn != null) conn.close()
} catch (SQLException se)
{ se.printStackTrace();
} // end finally try
} // end try
} //end main
} // end class

Downloaded by X Gaming (xmehedi1210@gmail.com)


lOMoARcPSD|50347845

What to know for tests/exams from this file:

You will not be expected to write JDBC code

You must be able to name, & explain, & state the purpose of:
JDBC
result sets
prepared statements
EXPLAIN
The remaining details in these slides are for future reference,
but not examinable.

Downloaded by X Gaming (xmehedi1210@gmail.com)

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy