SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Java Basics V3
Java Basics V3Java Basics V3
Java Basics V3
 
Exception Handling
Exception HandlingException Handling
Exception Handling
 
Java IO Streams V4
Java IO Streams V4Java IO Streams V4
Java IO Streams V4
 
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
 
JUnit 4
JUnit 4JUnit 4
JUnit 4
 
OOP V3.1
OOP V3.1OOP V3.1
OOP V3.1
 
JAVA Variables and Operators
JAVA Variables and OperatorsJAVA Variables and Operators
JAVA Variables and Operators
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
PDBC
PDBCPDBC
PDBC
 
Java Basics
Java BasicsJava Basics
Java Basics
 
CSS
CSS CSS
CSS
 
C++
C++C++
C++
 
Machine learning ( Part 3 )
Machine learning ( Part 3 )Machine learning ( Part 3 )
Machine learning ( Part 3 )
 
Machine learning ( Part 1 )
Machine learning ( Part 1 )Machine learning ( Part 1 )
Machine learning ( Part 1 )
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Angular 8
Angular 8 Angular 8
Angular 8
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
Java 8 Lambda Expressions
Java 8 Lambda ExpressionsJava 8 Lambda Expressions
Java 8 Lambda Expressions
 

Andere mochten auch (8)

Java Networking
Java NetworkingJava Networking
Java Networking
 
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
 

Ähnlich wie JDBC

Sql basics
Sql basicsSql basics
Sql basics
Kumar
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Net
webhostingguy
 
The sqlite3 commnad line tool
The sqlite3 commnad line toolThe sqlite3 commnad line tool
The sqlite3 commnad line tool
punu_82
 
New Features of SQL Server 2016
New Features of SQL Server 2016New Features of SQL Server 2016
New Features of SQL Server 2016
Mir Mahmood
 
MDI Training DB2 Course
MDI Training DB2 CourseMDI Training DB2 Course
MDI Training DB2 Course
Marcus Davage
 

Ähnlich wie JDBC (20)

Sql General
Sql General Sql General
Sql General
 
SQL Basics
SQL BasicsSQL Basics
SQL Basics
 
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
 

Mehr von Sunil OS (14)

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 )
 
Python Pandas
Python PandasPython Pandas
Python Pandas
 
Python part2 v1
Python part2 v1Python part2 v1
Python part2 v1
 
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 Basics
C BasicsC Basics
C Basics
 
Java Swing JFC
Java Swing JFCJava Swing JFC
Java Swing JFC
 

Kürzlich hochgeladen

Neurulation and the formation of the neural tube
Neurulation and the formation of the neural tubeNeurulation and the formation of the neural tube
Neurulation and the formation of the neural tube
SaadHumayun7
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
heathfieldcps1
 
IATP How-to Foreign Travel May 2024.pdff
IATP How-to Foreign Travel May 2024.pdffIATP How-to Foreign Travel May 2024.pdff
IATP How-to Foreign Travel May 2024.pdff
17thcssbs2
 

Kürzlich hochgeladen (20)

Essential Safety precautions during monsoon season
Essential Safety precautions during monsoon seasonEssential Safety precautions during monsoon season
Essential Safety precautions during monsoon season
 
Post Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdf
Post Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdfPost Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdf
Post Exam Fun(da) Intra UEM General Quiz 2024 - Prelims q&a.pdf
 
“O BEIJO” EM ARTE .
“O BEIJO” EM ARTE                       .“O BEIJO” EM ARTE                       .
“O BEIJO” EM ARTE .
 
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdfINU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
INU_CAPSTONEDESIGN_비밀번호486_업로드용 발표자료.pdf
 
An Overview of the Odoo 17 Discuss App.pptx
An Overview of the Odoo 17 Discuss App.pptxAn Overview of the Odoo 17 Discuss App.pptx
An Overview of the Odoo 17 Discuss App.pptx
 
Neurulation and the formation of the neural tube
Neurulation and the formation of the neural tubeNeurulation and the formation of the neural tube
Neurulation and the formation of the neural tube
 
size separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceuticssize separation d pharm 1st year pharmaceutics
size separation d pharm 1st year pharmaceutics
 
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
Basic Civil Engineering notes on Transportation Engineering, Modes of Transpo...
 
Championnat de France de Tennis de table/
Championnat de France de Tennis de table/Championnat de France de Tennis de table/
Championnat de France de Tennis de table/
 
Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).Dementia (Alzheimer & vasular dementia).
Dementia (Alzheimer & vasular dementia).
 
The basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptxThe basics of sentences session 4pptx.pptx
The basics of sentences session 4pptx.pptx
 
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & EngineeringBasic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
Basic Civil Engg Notes_Chapter-6_Environment Pollution & Engineering
 
REPRODUCTIVE TOXICITY STUDIE OF MALE AND FEMALEpptx
REPRODUCTIVE TOXICITY  STUDIE OF MALE AND FEMALEpptxREPRODUCTIVE TOXICITY  STUDIE OF MALE AND FEMALEpptx
REPRODUCTIVE TOXICITY STUDIE OF MALE AND FEMALEpptx
 
IATP How-to Foreign Travel May 2024.pdff
IATP How-to Foreign Travel May 2024.pdffIATP How-to Foreign Travel May 2024.pdff
IATP How-to Foreign Travel May 2024.pdff
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT VẬT LÝ 2024 - TỪ CÁC TRƯỜNG, TRƯ...
 
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
Incoming and Outgoing Shipments in 2 STEPS Using Odoo 17
 
Mbaye_Astou.Education Civica_Human Rights.pptx
Mbaye_Astou.Education Civica_Human Rights.pptxMbaye_Astou.Education Civica_Human Rights.pptx
Mbaye_Astou.Education Civica_Human Rights.pptx
 
philosophy and it's principles based on the life
philosophy and it's principles based on the lifephilosophy and it's principles based on the life
philosophy and it's principles based on the life
 
The Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. HenryThe Last Leaf, a short story by O. Henry
The Last Leaf, a short story by O. Henry
 
Application of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matricesApplication of Matrices in real life. Presentation on application of matrices
Application of Matrices in real life. Presentation on application of matrices
 

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