0% found this document useful (0 votes)
22 views18 pages

Intro To JDBC

Uploaded by

jyotsnas99
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)
22 views18 pages

Intro To JDBC

Uploaded by

jyotsnas99
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/ 18

Intro to JDBC

Dr.S.Nagender Kumar
Outline
• JDBC introduction
• JDBC Drivers
• Quick primer on relational databases
• Basic steps in using JDBC

2
JDBC Introduction
• Provides a standard library for accessing
relational databases
• JDBC API standardized
– Way to establish connection to database
– Approach for initiating queries
– Method to create stored (parameterized) queries
– The data structure of query result (table)
• Determining the number of columns, looking up
metadata, etc. 3
JDBC Drivers
• JDBC consists of two Java Application
JDBC API
parts JDBC Driver
Manager
JDBC Driver API
– JDBC API, a purely Java- JDBC-ODBC Vendor specific
Bridge JDBC Driver
based API
Vendor specific
– JDBC Driver Manager ODBC Driver

• Communicates with
Access SQL DB2 Oracle MySQL Sybase
vendor-specific drivers Server
that perform the real
communication with the
database
4
Types of JDBC Drivers
• Open Data Base Connectivity – ODBC
– Developed by Microsoft for the Windows platform & applications to
access Microsoft databases (SQL Server, Access etc.)
– Has become an industry standard
• Most database vendors supply native ODBC and JDBC drivers
• Type 1: JDBC-ODBC Bridge
– Translate JDBC into ODBC and use Windows ODBC built in drivers
• Type 2: Native API, partially java
– Converts JDBC to database vendors native SQL calls
• Type 3: JDBC Network Driver, partially java
– Translates JDBC to a DBMS independent network protocol
– Typically talks directly with a middleware product which in turn talks
tothe RDBMS e.g. Jaguar, DBAnywhere, SequeLink
• Type 4: 100% Java
– Converts JDBC directly to native API used by the RDBMS 5
Relational Databases
• A relational database is comprised of tables
• Each table represents a relation = collection of
tuples (rows)
• Each tuple consists of multiple fields
(columns)
Basic SQL Commands - Queries

https://mariadb.com/kb/en/library/basic-sql-statements/
Basic Steps in Using JDBC
Demo 1
• Load the driver
– Not required from Java 6
Class.forName("com.mysql.jdbc.Driver");
• Define the Connection URL
• Establish the Connection
• Create a Statement object
• Execute a query
• Process the results
• Close the connection
10/2/2020 8
Define the Connection URL
• A database connection is defined with a connection string
• Connection string contains information such as database
type, database name, server name, and port number
• Syntax of a MySQL connection string

jdbc:mysql://[host1][:port1][,[host2][:port2]]...[/[database]]
[?propertyName1=propertyValue1[&propertyName2=propert
yValue2]...]

jdbc:mysql://localhost:3306/ebookshop?useSSL=false&useUni
code=true&useJDBCCompliantTimezoneShift=true&useLegacy
DatetimeCode=false&serverTimezone=UTC
9
Establish the Connection
• Get the main connection

*****

• Optionally, look up info about the database DatabaseMetaData


dbMetaData = connection.getMetaData();
String productName =
dbMetaData.getDatabaseProductName();
String productVersion =
dbMetaData.getDatabaseProductVersion();
10
Further steps
• Create a Statement Demo 2
– A Statement is used to send queries or commands

• Execute a Query
– statement.executeQuery("SELECT ... FROM ...");
• returns a ResultSet
– statement.executeUpdate("UPDATE ...");
– statement.executeUpdate("INSERT ...");
– statement.executeUpdate("DELETE...");
– statement.execute("CREATE TABLE...");
11
– statement.execute("DROP TABLE ...");
Execute a Query - continued
String query = "insert into books values (1006, 'Fog and Edge
Computing: Principles and Paradigms', 'Rajkumar Buyya and ', 113,
50)";

• If we repeatedly executing query or update


where format stays consistent, but only values
change
– Statement is inefficient
12
PreparedStatement
Demo 3
• Make a placeholder

• PreparedStatement is significantly faster with


most drivers and databases
• Notice the index of inserter starts from 1
13
Process the Result
• executeQuery with Select SQL statement returns a ResultSet
• resultSet.next()
– Cursor goes to the next row
– Returns false if no next row
• resultSet.getString("columnName")
– Returns value of column with designated name in current row, as a String
– Also getInt, getDouble, getBlob, etc.
• resultSet.getString(columnIndex)
– Returns value of designated column
– First index is 1 (ala SQL), not 0 (ala Java)
• resultSet.beforeFirst()
– Moves cursor before first row, as it was initially
– first() moves the cursor to the first row
– Similarly for last() and afterLast() 14
• resultSet.absolute(rowNum)
Process the Result - continued
Demo 4
• Query is

15
Close the connection
• When totally done, close the database
connection
connection.close();
• However, opening a new connection is
typically much more expensive than sending
queries on existing connections
• Many JDBC drivers do automatic connection
pooling
16
Transaction support
• A transaction is an atomic unit of database
operations against the data
• The effects of all the SQL statements in a
transaction can either be committed or rolled
back
con.setAutoCommit(false);
st.executeUpdate()
st.executeUpdate()
con.commit(); //con.rollback();
17
Batch updates
• Use batch updates when we need to update
data with multiple statements
con.setAutoCommit(false);
st.addBatch("DROP TABLE …);
st.addBatch("CREATE TABLE …);
st.addBatch("INSERT INTO …);
st.addBatch("INSERT INTO …);
int counts[] = st.executeBatch(); 18

You might also like