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.
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)
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
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().
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 ;
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
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