SlideShare a Scribd company logo
1 of 54
www.sunilos.com
www.raystec.com
JDBC
www.SunilOS.com 2
SQL
It stands for Structured Query Language.
Standardized syntax for “querying”
(accessing) a relational database.
It is assumed that SQL is database
independent but there are important
variations from Database to Database.
www.SunilOS.com 3
Sales System Tables
Order
id date part_id qty
1 2/12/2006 1 100
2 3/15/2006 2 200
3 3/15/2006 3 100
4 4/5/2006 2 300
5 4/15/2006 3 200
6 6/15/2006 1 400
7 8/1/2006 1 100
Part
id name color unit_id
1 Nut Grey 2
2 Bolt Grey 3
3 Screw Silver 2
Unit
id city Capacity
1 New York 1000
2 London 2000
3 Paris 3000
Primary Key
Foreign Key
Foreign Key
Primary
Key
www.SunilOS.com 4
SQL Statements
 DDL data definition language
o Statement for defining tables
 Create & Alter Tables
o Statement for deleting tables
 Drop table
 DML data manipulation language
o Statement for Queries
 SELECT * FROM part;
o Statement for Inserting and Updating data
 INSERT into part VALUES(4,'plat','Green',1);
 UPDATE part SET color = 'Green', unit_id = 1 where id=4;
o Statement for deleting rows
 DELETE FROM part WHERE id=4;
 DCL – Data Control Language
o Commit : Saves data changes
o Rollback : Reverts data changes
o Savepoint : transaction demarcation.
www.SunilOS.com 5
DDL Statements
CREATE TABLE `part` (
`id` int(11) NOT NULL,
`name` text,
`color` text,
`unit_id` int(11) default NULL,
PRIMARY KEY (`id`)
)
ALTER TABLE `part`
ADD `color` text/
www.SunilOS.com 6
DML Statements
 Statement to insert all columns into part table.
INSERT INTO part VALUES (4,'plat','Green',1);
 Statement to insert id and name columns into part table.
INSERT INTO part (id,name) VALUES (4,'plat');
 Statement to update color and unit_id into part table.
UPDATE part SET color = 'Green', unit_id = 1 WHERE id=4;
 Statement to delete record from part table.
DELETE FROM part WHERE id=4;
www.SunilOS.com 7
DML - Select
Get all parts
o SELECT * FROM part;
Get all parts’ ids, names and colors
o SELECT id, name, color FROM part;
Get all grey color parts
o SELECT * FROM part WHERE color = ‘Grey’
Get all parts sorted by name
o SELECT * FROM part ORDER BY name
www.SunilOS.com 8
DML – Aggregate Functions
How many parts are there?
o SELECT count(*) from part;
o SELECT count(id) from part;
How many parts have been sold?
o SELECT sum(qty) from order
Which is the biggest deal so far?
o SELECT max(qty) from order;
Which is the minimum deal so far?
o SELECT min(qty) from order;
www.SunilOS.com 9
Joins
 Get parts with their cities of units.
o Columns :part.id, name, color, unit.city
o Tables :part & unit
o Condition:part.unit_id = unit.id;
 SELECT part.id, name, color, unit.city FROM part, unit
WHERE part.unit_id = unit.id;
www.SunilOS.com 10
Aliases
 SELECT p.id PartID, name, color, u.city FROM part p,
unit u WHERE p.unit_id = u.id
 Or
 SELECT p.id as PartID, name, color, u.city FROM
part as p, unit as u WHERE p.unit_id = u.id
SQL IN/BETWEEN
 Get the list of all Silver and Grey parts.
o SELECT * FROM part WHERE color IN ('Grey','Silver')
 Get orders those ordered quantities are between 100 to 200.
o SELECT * from orders WHERE qty BETWEEN 100 AND 200
 Get part counts for each color.
o SELECT color, count (*) part FROM part GROUP BY color
www.SunilOS.com 11
www.SunilOS.com 12
Nested Query
A Query can be nested in another query.
Get part ids those are ordered more than 100.
o SELECT part_id FROM orders WHERE qty > 100
Get part names those are ordered more than
100.
o SELECT name FROM part
o WHERE id IN
o ( SELECT part_id FROM orders WHERE qty > 100)
www.SunilOS.com 13
Joins
Outer Join
Inner Join
Left Join
Right Join
Joins
www.SunilOS.com 14
www.SunilOS.com 15
JDBC Overview
Java Database Connectivity
Latest Version 4.0
It is set of interfaces
www.SunilOS.com 16
History
Developer
2000
Oracle
Power
Builder
VB
Sybase
MSSQL
2- Tier System
Front End Back End
Tightly Coupled
www.SunilOS.com 17
ODBC – Open Database
Connectivity
Oracle
Power
Builder
VB
Sybase
MSSQL
2- Tier SystemFront End Back End
Loosely Coupled
Developer
2000
ODBC
ODBCODBCODBC
ODBCODBC
Java
JDBC
ODBC
www.SunilOS.com 18
Pure JDBC
Front End
Back End
DB
JDBC-ODBC Bridge
Drivers
ODBC
Java
JDBC
ODBC
Java
JDBC
Native
DB
Native Drivers
DB
Pure Java Drivers
JDBC
Java
JDBC
www.SunilOS.com 19
JDBC Ancestry
X/OPEN
ODBC
JDBC
www.SunilOS.com 20
Telecommunication
Service
Provider
BSNL
AirTel
Reliance
Listen
Speak
Statement
Driver
Manager
MySQL
Oracle
Sybase
ResultSet
/Record Count
Query
Connection
Connection
Drivers
www.SunilOS.com 21
MYSQL – Get Data
public static void main(String args[]) throws Exception{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root","root");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT id, name, color FROM part");
System.out.println("IDtNametColor");
while (rs.next()) {
System.out.print(rs.getString(1));
System.out.print("t" + rs.getString(2));
System.out.println("t" + rs.getString("color"));
}
stmt.close();
conn.close();
}
Load Driver
DB URL
Login ID
PWD
SQL Query
Column value by index
By DB Column name
www.SunilOS.com 22
Connect with Database
Here are the steps to be followed to make a
database call:
1. Load Driver
2. Make connection to the Database
3. Create statement
4. Execute query and get ResultSet or execute
insert/update/delete query and get number of records
affected
Note : Driver jar must be in classpath
www.SunilOS.com 23
MYSQL – Insert/Update Data
Class.forName("com.mysql.jdbc.Driver");//load Driver
Connection conn =
DriverManager.getConnection( "jdbc:mysql://localhost/test", "root",
"root"); //make connection
Statement stmt = conn.createStatement(); //create statement
//execute query
int i= stmt.executeUpdate(“INSERT into part values (4,'plat','Green',1)"); /
System.out.print( i + “ Record(s) Updated ”);
//close statements
stmt.close(); conn.close();
www.SunilOS.com 24
JDBC Class Usage
DriverManager
Driver
Connection
Statement
ResultSet
Class
Interface Driver jar contains concrete classes
of Interfaces
Factory of Connection
Factory of Statement
www.SunilOS.com 25
Statement Methods
 ResultSet executeQuery(String)
o Executes an SQL statement and returns a single ResultSet.
 int executeUpdate(String)
o Executes an SQL INSERT, UPDATE or DELETE statement and
returns the number of rows changed.
 boolean execute(String)
o Executes an SQL statement that may return multiple ResultSets.
www.SunilOS.com 26
JDBC URLs
jdbc:subprotocol:source
Each driver has its own sub-protocol.
Each sub-protocol has its own syntax to
connect to the source.
jdbc:odbc:DataSource
o e.g. jdbc:odbc:Northwind
jdbc:msql://host[:port]/database
o e.g. jdbc:msql://foo.nowhere.com:4333/accounting
jdbc:oracle://host[:port]/database
o e.g. jdbc:oracle://foo.nowhere.com:4333/accounting
www.SunilOS.com 27
Other Databases
 MS Access
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection conn = DriverManager.getConnection("jdbc:odbc:BATCH06", "", "");
Statement stmt = conn.createStatement();
 ORACLE
Class.forName(“oracle.jdbc.OracleDriver");
Connection conn = DriverManager.getConnection( "jdbc:oracle://localhost/orcl",
“scott", “tiger");
Statement stmt = conn.createStatement();
USER DSN
www.SunilOS.com 28
JDBC Drivers
DBJDBC ODBC
DBJDBC
Native
Driver
DBJDBC
Native
DriverJDBC
DB
JDBC
JDBC
Middleware
Client
Type 3
Type 2 - Native
Type 1 - Bridge
Type 4 – Pure
Java
www.SunilOS.com 29
JDBC Drivers
Type I : “Bridge”
Type II : “Native”
Type III : “Middleware”
Type IV : “Pure Java”
www.SunilOS.com 30
Type I Drivers
 Uses bridging technology.
 Requires installation/configuration on client machines.
 It is not recommended for Web Application.
 Example drivers are ODBC Bridge.
 How to Setup:
Create User DSN by: Control Panel-> Admin Tools-> Data Source-> User
DSN.
www.SunilOS.com 31
Type II Drivers
Native API drivers.
Requires installation/configuration on client
machines.
Used to leverage existing CLI libraries.
Usually not thread-safe.
Mostly obsolete now.
Example is Intersolv Oracle Driver, WebLogic
drivers.
www.SunilOS.com 32
Type III Drivers
It is also called middleware server, usually installed
at database host.
Very flexible, allows access to multiple databases
using one driver.
Installation of driver is required only on a single
machine, it is another server application to install
and maintain.
Example driver is Symantec DBAnywhere.
www.SunilOS.com 33
Type IV Drivers
 100% Pure Java.
 Use Java networking libraries to talk directly to the
databases.
 Configuration requires only JARS to be CLASSPATH.
 Available for all modern databases.
www.SunilOS.com 34
java.sql.Connection Methods
Statement createStatement()
o returns a new Statement object.
PreparedStatement
prepareStatement(String sql)
o returns a new PreparedStatement object
CallableStatement
prepareCall(String sql)
o returns a new CallableStatement object
www.SunilOS.com 35
JDBC Class Diagram
www.SunilOS.com 36
Prepared Statement
Statement stmt = conn.createStatement();
String sql =“INSERT into part values (4,'plat','Green',1)“;
int i= stmt.executeUpdate(sql);
OR
int id = 4; String name =“plat”; String color = “Green”, int unitId=1;
String sql = “INSERT into part values (“+ id +”,‘” + name + ”',‘”+color + ”',” + unitId +”)"
int i= stmt.executeUpdate(sql);
OR
int id = 4; String name =“plat”; String color = “Green”, int unitId=1;
PreparedStatement ps = conn.prepareStatement(“INSERT into part values (?,?,?,?)")
ps.setInt(1,id);
ps.setString(2,name);
ps.setString(3,color);
ps.setInt(4,unitId);
int i = ps.executeUpdate();
www.SunilOS.com 37
PreparedStatement
 It is given SQL statement while creation.
 SQL Statements are optimized (pre-compiled) before
execution.
 In PreparedStatement database retains the precompiled
(optimized) SQL statement whereas Statement does NOT
retain precompiled SQL statement.
 It is recommended to use when same SQL statement is to
be called multiple times with different parameter values.
 By default PreparedStatement is recommended to use over
Statement.
www.SunilOS.com 38
Stored Procedures
It is written in database specific language.
It is stored in database.
It is accessed by CallableStatement.
CallableStatement is created by
Connection.prepareCall().
www.SunilOS.com 39
Call to a Stored Procedure
 Class.forName("com.mysql.jdbc.Driver");
 Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost/test", “login", “pass");
 CallableStatement callStmt = conn.prepareCall("{CALL userCount(?)}");
 callStmt.registerOutParameter(1, Types.INTEGER);
 callStmt.execute();
 int count = callStmt.getInt(1);
 System.out.println(" Count " + count );
www.SunilOS.com 40
MYSQL – User Count
DELIMITER $$
DROP PROCEDURE IF EXISTS `test`.`userCount`$$
CREATE PROCEDURE `test`.`userCount` (OUT c INTEGER)
BEGIN
SELECT count(*) FROM users INTO c ;
END$$
DELIMITER ;
www.SunilOS.com 41
MYSQL – User Count
DELIMITER $$
DROP FUNCTION IF EXISTS `test`.`userCount`$$
CREATE FUNCTION `test`.`userCount` ()
TYPE INTEGER
BEGIN
DECLARE c INTEGER;
SELECT count(*) FROM users INTO c ;
RETURN c;
END$$
DELIMITER ;
www.SunilOS.com 42
Call to a Stored Function
 Class.forName("com.mysql.jdbc.Driver");
 Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost/test", “login", “pass");
 CallableStatement callStmt = conn.prepareCall("{? = CALL userCount(?,?)}");
 callStmt.registerOutParameter(1, Types.INTEGER);
 callStmt.setString(2,”Vijay”); //Set parameters
 callStmt.setInt(3,100);
 callStmt.execute();
 System.out.println(" Count " + callStmt.getInt(1));
www.SunilOS.com 43
Transaction Handling
 A transaction is a set of data changes made by multiple
SQL statements. Entire changes of this set will be either
committed (saved) or rolled back (reverted) together.
 By default each statement is committed irrespective of
others failures.
 Transaction begins by:
o connection.setAutoCommit(false);
o Default value of auto commit is true.
 Transaction ends by calling:
o connection.commit()
o conncetion.rollback();
www.SunilOS.com 44
Transaction Handling : Commit
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test",
“login", “pass");
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
int i= stmt.executeUpdate(“INSERT into part values (1,'plat','Green',1)");
i= stmt.executeUpdate(“INSERT into unit values (2,‘London',3000)");
conn.commit();
stmt.close();
conn.close();
www.SunilOS.com 45
Exception Handling : Rollback
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test",
“login", “pass");
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();
try{
int i= stmt.executeUpdate(“INSERT into part values (1,'plat','Green',1)");
i= stmt.executeUpdate(“INSERT into unit values (2,‘London',3000)");
conn.commit();
}catch (SQLException e){
conn.rollback();
}
stmt.close(); conn.close();
}
www.SunilOS.com 46
Mapping Java Types to SQL Types
SQL type Java Type
CHAR, VARCHAR, LONGVARCHAR String
NUMERIC, DECIMAL java.math.BigDecimal
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT, DOUBLE double
BINARY, VARBINARY, LONGVARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
Date + Time
(Nano sec)
www.SunilOS.com 47
Database Time
Java defines three classes to handle date and time:
java.sql.Date
o year, month, day
java.sql.Time
o hours, minutes, seconds
java.sql.Timestamp
o year, month, day, hours, minutes, seconds, nanoseconds
o By default Timestamp should be used
www.SunilOS.com 48
Metadata – Data about Data
 ResultSet rs = stmt.executeQuery("SELECT id, name, color from part");
 ResultSetMetaData rsmt = rs.getMetaData();
 System.out.println("Catelog Name : " + rsmt.getCatalogName(1));
 System.out.println("Table Name : " + rsmt.getTableName(1));
 int columnCount = rsmt.getColumnCount();
 System.out.println("Total Columns :" + columnCount);
www.SunilOS.com 49
Metadata – Data about Data
 for (int i = 1; i <= columnCount; i++) {
o System.out.println("Column :" + (i));
o System.out.println("Label : " + rsmt.getColumnLabel(i));
o System.out.println("Name : " + rsmt.getColumnName(i));
o System.out.println("Type : " + rsmt.getColumnTypeName(i));
o System.out.println("Size : " + rsmt.getColumnDisplaySize(i));
o System.out.println("Precision : " + rsmt.getPrecision(i));
o System.out.println();
 }
www.SunilOS.com 50
Metadata - Output
Catelog Name : test
Table Name : part
Total Columns :3
Column :1
Label : id
Name : id
Type : INTEGER
Size : 11
Precision : 11
Column :2
Label : name
Name : name
Type : VARCHAR
Size : 65535
Precision : 65535
Column :3
Label : color
Name : color
Type : VARCHAR
Size : 65535
Precision : 65535
www.SunilOS.com 51
Javabean
public class Marksheet {
private String rollNo = null;
private String name = null;
private int chemistry = 0;
private int physics = 0;
private int maths = 0;
public Marksheet(){}//Def
Constructor
public String getRollNO() {
return rollNo ;
}
public void setRollN(String rollNo)
{
this.rollNo = rollNo ;
}
..Other Setter/Getter
Marksheet
-rollNo : String
-name : String
-chemistry : int
-physics : int
-maths:int
+setters
+getters
www.SunilOS.com 52
Model
MarksheetModel
+ add (Marksheet)
+ update (Marksheet)
+ delete (rollNo) : Marksheet
+ get (rollNo) : Marksheet
+getMeritList(): ArrayList
+search(Marksheet)
TestMarksheetModel
+ testAdd ()
+ testUpdate ()
+ testDelete ()
+ testGet ()
+testGetMeritList()
+testSearch()
+main(String[])
Disclaimer
This is an educational presentation to enhance the
skill of computer science students.
This presentation is available for free to computer
science students.
Some internet images from different URLs are
used in this presentation to simplify technical
examples and correlate examples with the real
world.
We are grateful to owners of these URLs and
pictures.
www.SunilOS.com 53
Thank You!
www.SunilOS.com 54
www.SunilOS.com

More Related Content

What's hot

Resource Bundle
Resource BundleResource Bundle
Resource BundleSunil OS
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4Sunil OS
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and OperatorsSunil OS
 
JavaScript
JavaScriptJavaScript
JavaScriptSunil OS
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File HandlingSunil OS
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and ConcurrencySunil OS
 
Java Basics
Java BasicsJava Basics
Java BasicsSunil OS
 
Java Networking
Java NetworkingJava Networking
Java NetworkingSunil OS
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with JavaJussi Pohjolainen
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )Sunil OS
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFCSunil OS
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaEdureka!
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Edureka!
 

What's hot (20)

OOP V3.1
OOP V3.1OOP V3.1
OOP V3.1
 
Resource Bundle
Resource BundleResource Bundle
Resource Bundle
 
Log4 J
Log4 JLog4 J
Log4 J
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Java Input Output and File Handling
Java Input Output and File HandlingJava Input Output and File Handling
Java Input Output and File Handling
 
Java Threads and Concurrency
Java Threads and ConcurrencyJava Threads and Concurrency
Java Threads and Concurrency
 
Java Basics
Java BasicsJava Basics
Java Basics
 
CSS
CSS CSS
CSS
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFC
 
PDBC
PDBCPDBC
PDBC
 
Java Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | EdurekaJava Design Patterns Tutorial | Edureka
Java Design Patterns Tutorial | Edureka
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
 

Viewers also liked

Open Distributed Networking Intelligence: A New Java Paradigm
Open Distributed Networking Intelligence: A New Java ParadigmOpen Distributed Networking Intelligence: A New Java Paradigm
Open Distributed Networking Intelligence: A New Java ParadigmTal Lavian Ph.D.
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket ProgrammingMousmi Pawar
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPTkamal kotecha
 

Viewers also liked (7)

java networking
 java networking java networking
java networking
 
Open Distributed Networking Intelligence: A New Java Paradigm
Open Distributed Networking Intelligence: A New Java ParadigmOpen Distributed Networking Intelligence: A New Java Paradigm
Open Distributed Networking Intelligence: A New Java Paradigm
 
javanetworking
javanetworkingjavanetworking
javanetworking
 
Networking Java Socket Programming
Networking Java Socket ProgrammingNetworking Java Socket Programming
Networking Java Socket Programming
 
Socket programming
Socket programmingSocket programming
Socket programming
 
Network programming in java - PPT
Network programming in java - PPTNetwork programming in java - PPT
Network programming in java - PPT
 
Slideshare ppt
Slideshare pptSlideshare ppt
Slideshare ppt
 

Similar to JDBC

Sql basics
Sql basicsSql basics
Sql basicsKumar
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Netwebhostingguy
 
The sqlite3 commnad line tool
The sqlite3 commnad line toolThe sqlite3 commnad line tool
The sqlite3 commnad line toolpunu_82
 
New Features of SQL Server 2016
New Features of SQL Server 2016New Features of SQL Server 2016
New Features of SQL Server 2016Mir Mahmood
 
MDI Training DB2 Course
MDI Training DB2 CourseMDI Training DB2 Course
MDI Training DB2 CourseMarcus Davage
 
War of the Indices- SQL Server and Oracle
War of the Indices-  SQL Server and OracleWar of the Indices-  SQL Server and Oracle
War of the Indices- SQL Server and OracleKellyn Pot'Vin-Gorman
 
All Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesAll Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesDave Stokes
 
IBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql FeaturesIBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql FeaturesKeshav Murthy
 
RMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRsquared Academy
 

Similar to JDBC (20)

Sql basics
Sql basicsSql basics
Sql basics
 
Sql General
Sql General Sql General
Sql General
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Net
 
User Group3009
User Group3009User Group3009
User Group3009
 
The sqlite3 commnad line tool
The sqlite3 commnad line toolThe sqlite3 commnad line tool
The sqlite3 commnad line tool
 
New Features of SQL Server 2016
New Features of SQL Server 2016New Features of SQL Server 2016
New Features of SQL Server 2016
 
MDI Training DB2 Course
MDI Training DB2 CourseMDI Training DB2 Course
MDI Training DB2 Course
 
War of the Indices- SQL Server and Oracle
War of the Indices-  SQL Server and OracleWar of the Indices-  SQL Server and Oracle
War of the Indices- SQL Server and Oracle
 
Introduction to SQL
Introduction to SQLIntroduction to SQL
Introduction to SQL
 
All Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for NewbiesAll Things Open 2016 -- Database Programming for Newbies
All Things Open 2016 -- Database Programming for Newbies
 
IBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql FeaturesIBM Informix dynamic server 11 10 Cheetah Sql Features
IBM Informix dynamic server 11 10 Cheetah Sql Features
 
B_110500002
B_110500002B_110500002
B_110500002
 
Lecture5-SQL.docx
Lecture5-SQL.docxLecture5-SQL.docx
Lecture5-SQL.docx
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
Intake 37 ef2
Intake 37 ef2Intake 37 ef2
Intake 37 ef2
 
Jdbc
JdbcJdbc
Jdbc
 
Oracle notes
Oracle notesOracle notes
Oracle notes
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
RMySQL Tutorial For Beginners
RMySQL Tutorial For BeginnersRMySQL Tutorial For Beginners
RMySQL Tutorial For Beginners
 

More from Sunil OS

Threads v3
Threads v3Threads v3
Threads v3Sunil OS
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3Sunil OS
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )Sunil OS
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )Sunil OS
 
Python Pandas
Python PandasPython Pandas
Python PandasSunil OS
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1Sunil OS
 
Angular 8
Angular 8 Angular 8
Angular 8 Sunil OS
 
Python Part 1
Python Part 1Python Part 1
Python Part 1Sunil OS
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and OperatorsSunil OS
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays TechnologiesSunil OS
 

More from Sunil OS (16)

DJango
DJangoDJango
DJango
 
OOP v3
OOP v3OOP v3
OOP v3
 
Threads v3
Threads v3Threads v3
Threads v3
 
Exception Handling v3
Exception Handling v3Exception Handling v3
Exception Handling v3
 
Machine learning ( Part 2 )
Machine learning ( Part 2 )Machine learning ( Part 2 )
Machine learning ( Part 2 )
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1
 
Angular 8
Angular 8 Angular 8
Angular 8
 
Python Part 1
Python Part 1Python Part 1
Python Part 1
 
C# Variables and Operators
C# Variables and OperatorsC# Variables and Operators
C# Variables and Operators
 
C# Basics
C# BasicsC# Basics
C# Basics
 
Rays Technologies
Rays TechnologiesRays Technologies
Rays Technologies
 
C++ oop
C++ oopC++ oop
C++ oop
 
C++
C++C++
C++
 
C Basics
C BasicsC Basics
C Basics
 

Recently uploaded

How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPCeline George
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxChelloAnnAsuncion2
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationAadityaSharma884161
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayMakMakNepo
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxthorishapillay1
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxsqpmdrvczh
 

Recently uploaded (20)

How to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERPHow to do quick user assign in kanban in Odoo 17 ERP
How to do quick user assign in kanban in Odoo 17 ERP
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptxGrade 9 Q4-MELC1-Active and Passive Voice.pptx
Grade 9 Q4-MELC1-Active and Passive Voice.pptx
 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
ROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint PresentationROOT CAUSE ANALYSIS PowerPoint Presentation
ROOT CAUSE ANALYSIS PowerPoint Presentation
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Quarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up FridayQuarter 4 Peace-education.pptx Catch Up Friday
Quarter 4 Peace-education.pptx Catch Up Friday
 
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Bikash Puri  Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Bikash Puri Delhi reach out to us at 🔝9953056974🔝
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Proudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptxProudly South Africa powerpoint Thorisha.pptx
Proudly South Africa powerpoint Thorisha.pptx
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
Romantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptxRomantic Opera MUSIC FOR GRADE NINE pptx
Romantic Opera MUSIC FOR GRADE NINE pptx
 

JDBC

  • 2. www.SunilOS.com 2 SQL It stands for Structured Query Language. Standardized syntax for “querying” (accessing) a relational database. It is assumed that SQL is database independent but there are important variations from Database to Database.
  • 3. www.SunilOS.com 3 Sales System Tables Order id date part_id qty 1 2/12/2006 1 100 2 3/15/2006 2 200 3 3/15/2006 3 100 4 4/5/2006 2 300 5 4/15/2006 3 200 6 6/15/2006 1 400 7 8/1/2006 1 100 Part id name color unit_id 1 Nut Grey 2 2 Bolt Grey 3 3 Screw Silver 2 Unit id city Capacity 1 New York 1000 2 London 2000 3 Paris 3000 Primary Key Foreign Key Foreign Key Primary Key
  • 4. www.SunilOS.com 4 SQL Statements  DDL data definition language o Statement for defining tables  Create & Alter Tables o Statement for deleting tables  Drop table  DML data manipulation language o Statement for Queries  SELECT * FROM part; o Statement for Inserting and Updating data  INSERT into part VALUES(4,'plat','Green',1);  UPDATE part SET color = 'Green', unit_id = 1 where id=4; o Statement for deleting rows  DELETE FROM part WHERE id=4;  DCL – Data Control Language o Commit : Saves data changes o Rollback : Reverts data changes o Savepoint : transaction demarcation.
  • 5. www.SunilOS.com 5 DDL Statements CREATE TABLE `part` ( `id` int(11) NOT NULL, `name` text, `color` text, `unit_id` int(11) default NULL, PRIMARY KEY (`id`) ) ALTER TABLE `part` ADD `color` text/
  • 6. www.SunilOS.com 6 DML Statements  Statement to insert all columns into part table. INSERT INTO part VALUES (4,'plat','Green',1);  Statement to insert id and name columns into part table. INSERT INTO part (id,name) VALUES (4,'plat');  Statement to update color and unit_id into part table. UPDATE part SET color = 'Green', unit_id = 1 WHERE id=4;  Statement to delete record from part table. DELETE FROM part WHERE id=4;
  • 7. www.SunilOS.com 7 DML - Select Get all parts o SELECT * FROM part; Get all parts’ ids, names and colors o SELECT id, name, color FROM part; Get all grey color parts o SELECT * FROM part WHERE color = ‘Grey’ Get all parts sorted by name o SELECT * FROM part ORDER BY name
  • 8. www.SunilOS.com 8 DML – Aggregate Functions How many parts are there? o SELECT count(*) from part; o SELECT count(id) from part; How many parts have been sold? o SELECT sum(qty) from order Which is the biggest deal so far? o SELECT max(qty) from order; Which is the minimum deal so far? o SELECT min(qty) from order;
  • 9. www.SunilOS.com 9 Joins  Get parts with their cities of units. o Columns :part.id, name, color, unit.city o Tables :part & unit o Condition:part.unit_id = unit.id;  SELECT part.id, name, color, unit.city FROM part, unit WHERE part.unit_id = unit.id;
  • 10. www.SunilOS.com 10 Aliases  SELECT p.id PartID, name, color, u.city FROM part p, unit u WHERE p.unit_id = u.id  Or  SELECT p.id as PartID, name, color, u.city FROM part as p, unit as u WHERE p.unit_id = u.id
  • 11. SQL IN/BETWEEN  Get the list of all Silver and Grey parts. o SELECT * FROM part WHERE color IN ('Grey','Silver')  Get orders those ordered quantities are between 100 to 200. o SELECT * from orders WHERE qty BETWEEN 100 AND 200  Get part counts for each color. o SELECT color, count (*) part FROM part GROUP BY color www.SunilOS.com 11
  • 12. www.SunilOS.com 12 Nested Query A Query can be nested in another query. Get part ids those are ordered more than 100. o SELECT part_id FROM orders WHERE qty > 100 Get part names those are ordered more than 100. o SELECT name FROM part o WHERE id IN o ( SELECT part_id FROM orders WHERE qty > 100)
  • 13. www.SunilOS.com 13 Joins Outer Join Inner Join Left Join Right Join
  • 15. www.SunilOS.com 15 JDBC Overview Java Database Connectivity Latest Version 4.0 It is set of interfaces
  • 17. www.SunilOS.com 17 ODBC – Open Database Connectivity Oracle Power Builder VB Sybase MSSQL 2- Tier SystemFront End Back End Loosely Coupled Developer 2000 ODBC ODBCODBCODBC ODBCODBC Java JDBC ODBC
  • 18. www.SunilOS.com 18 Pure JDBC Front End Back End DB JDBC-ODBC Bridge Drivers ODBC Java JDBC ODBC Java JDBC Native DB Native Drivers DB Pure Java Drivers JDBC Java JDBC
  • 21. www.SunilOS.com 21 MYSQL – Get Data public static void main(String args[]) throws Exception{ Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root","root"); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT id, name, color FROM part"); System.out.println("IDtNametColor"); while (rs.next()) { System.out.print(rs.getString(1)); System.out.print("t" + rs.getString(2)); System.out.println("t" + rs.getString("color")); } stmt.close(); conn.close(); } Load Driver DB URL Login ID PWD SQL Query Column value by index By DB Column name
  • 22. www.SunilOS.com 22 Connect with Database Here are the steps to be followed to make a database call: 1. Load Driver 2. Make connection to the Database 3. Create statement 4. Execute query and get ResultSet or execute insert/update/delete query and get number of records affected Note : Driver jar must be in classpath
  • 23. www.SunilOS.com 23 MYSQL – Insert/Update Data Class.forName("com.mysql.jdbc.Driver");//load Driver Connection conn = DriverManager.getConnection( "jdbc:mysql://localhost/test", "root", "root"); //make connection Statement stmt = conn.createStatement(); //create statement //execute query int i= stmt.executeUpdate(“INSERT into part values (4,'plat','Green',1)"); / System.out.print( i + “ Record(s) Updated ”); //close statements stmt.close(); conn.close();
  • 24. www.SunilOS.com 24 JDBC Class Usage DriverManager Driver Connection Statement ResultSet Class Interface Driver jar contains concrete classes of Interfaces Factory of Connection Factory of Statement
  • 25. www.SunilOS.com 25 Statement Methods  ResultSet executeQuery(String) o Executes an SQL statement and returns a single ResultSet.  int executeUpdate(String) o Executes an SQL INSERT, UPDATE or DELETE statement and returns the number of rows changed.  boolean execute(String) o Executes an SQL statement that may return multiple ResultSets.
  • 26. www.SunilOS.com 26 JDBC URLs jdbc:subprotocol:source Each driver has its own sub-protocol. Each sub-protocol has its own syntax to connect to the source. jdbc:odbc:DataSource o e.g. jdbc:odbc:Northwind jdbc:msql://host[:port]/database o e.g. jdbc:msql://foo.nowhere.com:4333/accounting jdbc:oracle://host[:port]/database o e.g. jdbc:oracle://foo.nowhere.com:4333/accounting
  • 27. www.SunilOS.com 27 Other Databases  MS Access Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection conn = DriverManager.getConnection("jdbc:odbc:BATCH06", "", ""); Statement stmt = conn.createStatement();  ORACLE Class.forName(“oracle.jdbc.OracleDriver"); Connection conn = DriverManager.getConnection( "jdbc:oracle://localhost/orcl", “scott", “tiger"); Statement stmt = conn.createStatement(); USER DSN
  • 28. www.SunilOS.com 28 JDBC Drivers DBJDBC ODBC DBJDBC Native Driver DBJDBC Native DriverJDBC DB JDBC JDBC Middleware Client Type 3 Type 2 - Native Type 1 - Bridge Type 4 – Pure Java
  • 29. www.SunilOS.com 29 JDBC Drivers Type I : “Bridge” Type II : “Native” Type III : “Middleware” Type IV : “Pure Java”
  • 30. www.SunilOS.com 30 Type I Drivers  Uses bridging technology.  Requires installation/configuration on client machines.  It is not recommended for Web Application.  Example drivers are ODBC Bridge.  How to Setup: Create User DSN by: Control Panel-> Admin Tools-> Data Source-> User DSN.
  • 31. www.SunilOS.com 31 Type II Drivers Native API drivers. Requires installation/configuration on client machines. Used to leverage existing CLI libraries. Usually not thread-safe. Mostly obsolete now. Example is Intersolv Oracle Driver, WebLogic drivers.
  • 32. www.SunilOS.com 32 Type III Drivers It is also called middleware server, usually installed at database host. Very flexible, allows access to multiple databases using one driver. Installation of driver is required only on a single machine, it is another server application to install and maintain. Example driver is Symantec DBAnywhere.
  • 33. www.SunilOS.com 33 Type IV Drivers  100% Pure Java.  Use Java networking libraries to talk directly to the databases.  Configuration requires only JARS to be CLASSPATH.  Available for all modern databases.
  • 34. www.SunilOS.com 34 java.sql.Connection Methods Statement createStatement() o returns a new Statement object. PreparedStatement prepareStatement(String sql) o returns a new PreparedStatement object CallableStatement prepareCall(String sql) o returns a new CallableStatement object
  • 36. www.SunilOS.com 36 Prepared Statement Statement stmt = conn.createStatement(); String sql =“INSERT into part values (4,'plat','Green',1)“; int i= stmt.executeUpdate(sql); OR int id = 4; String name =“plat”; String color = “Green”, int unitId=1; String sql = “INSERT into part values (“+ id +”,‘” + name + ”',‘”+color + ”',” + unitId +”)" int i= stmt.executeUpdate(sql); OR int id = 4; String name =“plat”; String color = “Green”, int unitId=1; PreparedStatement ps = conn.prepareStatement(“INSERT into part values (?,?,?,?)") ps.setInt(1,id); ps.setString(2,name); ps.setString(3,color); ps.setInt(4,unitId); int i = ps.executeUpdate();
  • 37. www.SunilOS.com 37 PreparedStatement  It is given SQL statement while creation.  SQL Statements are optimized (pre-compiled) before execution.  In PreparedStatement database retains the precompiled (optimized) SQL statement whereas Statement does NOT retain precompiled SQL statement.  It is recommended to use when same SQL statement is to be called multiple times with different parameter values.  By default PreparedStatement is recommended to use over Statement.
  • 38. www.SunilOS.com 38 Stored Procedures It is written in database specific language. It is stored in database. It is accessed by CallableStatement. CallableStatement is created by Connection.prepareCall().
  • 39. www.SunilOS.com 39 Call to a Stored Procedure  Class.forName("com.mysql.jdbc.Driver");  Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", “login", “pass");  CallableStatement callStmt = conn.prepareCall("{CALL userCount(?)}");  callStmt.registerOutParameter(1, Types.INTEGER);  callStmt.execute();  int count = callStmt.getInt(1);  System.out.println(" Count " + count );
  • 40. www.SunilOS.com 40 MYSQL – User Count DELIMITER $$ DROP PROCEDURE IF EXISTS `test`.`userCount`$$ CREATE PROCEDURE `test`.`userCount` (OUT c INTEGER) BEGIN SELECT count(*) FROM users INTO c ; END$$ DELIMITER ;
  • 41. www.SunilOS.com 41 MYSQL – User Count DELIMITER $$ DROP FUNCTION IF EXISTS `test`.`userCount`$$ CREATE FUNCTION `test`.`userCount` () TYPE INTEGER BEGIN DECLARE c INTEGER; SELECT count(*) FROM users INTO c ; RETURN c; END$$ DELIMITER ;
  • 42. www.SunilOS.com 42 Call to a Stored Function  Class.forName("com.mysql.jdbc.Driver");  Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", “login", “pass");  CallableStatement callStmt = conn.prepareCall("{? = CALL userCount(?,?)}");  callStmt.registerOutParameter(1, Types.INTEGER);  callStmt.setString(2,”Vijay”); //Set parameters  callStmt.setInt(3,100);  callStmt.execute();  System.out.println(" Count " + callStmt.getInt(1));
  • 43. www.SunilOS.com 43 Transaction Handling  A transaction is a set of data changes made by multiple SQL statements. Entire changes of this set will be either committed (saved) or rolled back (reverted) together.  By default each statement is committed irrespective of others failures.  Transaction begins by: o connection.setAutoCommit(false); o Default value of auto commit is true.  Transaction ends by calling: o connection.commit() o conncetion.rollback();
  • 44. www.SunilOS.com 44 Transaction Handling : Commit Class.forName("com.mysql.jdbc.Driver"); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", “login", “pass"); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); int i= stmt.executeUpdate(“INSERT into part values (1,'plat','Green',1)"); i= stmt.executeUpdate(“INSERT into unit values (2,‘London',3000)"); conn.commit(); stmt.close(); conn.close();
  • 45. www.SunilOS.com 45 Exception Handling : Rollback Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test", “login", “pass"); conn.setAutoCommit(false); Statement stmt = conn.createStatement(); try{ int i= stmt.executeUpdate(“INSERT into part values (1,'plat','Green',1)"); i= stmt.executeUpdate(“INSERT into unit values (2,‘London',3000)"); conn.commit(); }catch (SQLException e){ conn.rollback(); } stmt.close(); conn.close(); }
  • 46. www.SunilOS.com 46 Mapping Java Types to SQL Types SQL type Java Type CHAR, VARCHAR, LONGVARCHAR String NUMERIC, DECIMAL java.math.BigDecimal BIT boolean TINYINT byte SMALLINT short INTEGER int BIGINT long REAL float FLOAT, DOUBLE double BINARY, VARBINARY, LONGVARBINARY byte[] DATE java.sql.Date TIME java.sql.Time TIMESTAMP java.sql.Timestamp Date + Time (Nano sec)
  • 47. www.SunilOS.com 47 Database Time Java defines three classes to handle date and time: java.sql.Date o year, month, day java.sql.Time o hours, minutes, seconds java.sql.Timestamp o year, month, day, hours, minutes, seconds, nanoseconds o By default Timestamp should be used
  • 48. www.SunilOS.com 48 Metadata – Data about Data  ResultSet rs = stmt.executeQuery("SELECT id, name, color from part");  ResultSetMetaData rsmt = rs.getMetaData();  System.out.println("Catelog Name : " + rsmt.getCatalogName(1));  System.out.println("Table Name : " + rsmt.getTableName(1));  int columnCount = rsmt.getColumnCount();  System.out.println("Total Columns :" + columnCount);
  • 49. www.SunilOS.com 49 Metadata – Data about Data  for (int i = 1; i <= columnCount; i++) { o System.out.println("Column :" + (i)); o System.out.println("Label : " + rsmt.getColumnLabel(i)); o System.out.println("Name : " + rsmt.getColumnName(i)); o System.out.println("Type : " + rsmt.getColumnTypeName(i)); o System.out.println("Size : " + rsmt.getColumnDisplaySize(i)); o System.out.println("Precision : " + rsmt.getPrecision(i)); o System.out.println();  }
  • 50. www.SunilOS.com 50 Metadata - Output Catelog Name : test Table Name : part Total Columns :3 Column :1 Label : id Name : id Type : INTEGER Size : 11 Precision : 11 Column :2 Label : name Name : name Type : VARCHAR Size : 65535 Precision : 65535 Column :3 Label : color Name : color Type : VARCHAR Size : 65535 Precision : 65535
  • 51. www.SunilOS.com 51 Javabean public class Marksheet { private String rollNo = null; private String name = null; private int chemistry = 0; private int physics = 0; private int maths = 0; public Marksheet(){}//Def Constructor public String getRollNO() { return rollNo ; } public void setRollN(String rollNo) { this.rollNo = rollNo ; } ..Other Setter/Getter Marksheet -rollNo : String -name : String -chemistry : int -physics : int -maths:int +setters +getters
  • 52. www.SunilOS.com 52 Model MarksheetModel + add (Marksheet) + update (Marksheet) + delete (rollNo) : Marksheet + get (rollNo) : Marksheet +getMeritList(): ArrayList +search(Marksheet) TestMarksheetModel + testAdd () + testUpdate () + testDelete () + testGet () +testGetMeritList() +testSearch() +main(String[])
  • 53. Disclaimer This is an educational presentation to enhance the skill of computer science students. This presentation is available for free to computer science students. Some internet images from different URLs are used in this presentation to simplify technical examples and correlate examples with the real world. We are grateful to owners of these URLs and pictures. www.SunilOS.com 53