Network Programming in Java
Network Programming in Java
JDBC
Database
Database
Language
Select * from emp; Select * from emp where salary < 50000; Delete * from emp
Database Connectivity
HOW?
Database Connectivity
Middleware API
ODBC
ODBC
Driver manager
Driver 1
Driver 2
Driver 3
Driver 4
Database Access
Two Tier
Middleware API
Application Layer Client Side Server Side Database Layer Two tier Architecture
Two Tier
Pros
Simplicity Scalability
Cons
Three Tier
Application Layer middle Layer Client Side Server Side Database Layer Three tier Architecture
Three Tier
Three tier
Pros
Performance Complexity
Cons
Why JDBC?
ODBC is c based interface to sql based database. ODBC not appropriate for direct use in java JDBC needed to provide pure java solution.
JDBC Drivers
Type-1 Driver
The Type 1 driver translates all JDBC calls into ODBC calls and sends them to the ODBC driver. The JDBC-ODBC Bridge driver is recommended only for experimental use or when no other alternative is available
T y p 1 e -
O D B C
Type-1 Driver-Disadvantage
Since the Bridge driver is not written fully in Java, Type 1 drivers are not portable. A performance issue is seen as a JDBC call goes through the bridge to the ODBC driver, then to the database, and this applies even in the reverse process. They are the slowest of all driver types.
The client system requires the ODBC Installation to use the driver.
Type-2 Driver
Type 2 drivers convert JDBC calls into database-specific calls i.e. this driver is specific to a particular database.
T y p 2 e -
N a a t p i i v e
Type-2 Driver
Like Type 1 drivers, its not written in Java Language which forms a portability issue. Native API must be installed in the Client System and hence type 2 drivers cannot be used for the Internet.
Type-3 Driver
Type 3 database requests are passed through the network to the middle-tier server. The middle-tier then translates the request to the database. If the middletier server can in turn use Type1, Type 2 or Type 4 drivers.
T y p 3 e -
N e t k w o r
Type-3 Driver
It requires another server application to install and maintain. Traversing the recordset may take longer, since the data comes through the backend server.
Type-4
The Type 4 uses java networking libraries to communicate directly with the database server
JDBC Drivers
Type I Bridge ODBC Driver
ODBC
JDBC
Type II Native
CLI (.lib)
Middleware Server
Type IV Pure
Program
1. Import jdbc package.
2. Load Driver.
4. Execute query.
6. Close Connection
Step1
import java.sql.*; class one {
Step 2.
import java.sql.*; class one { public static void main(String arg[]) { Class.forname(sun.jdbc.odbc.JdbcOdbcDriver)
} }
This is driver class. Full class name with package name.
Step 2.
import java.sql.*; class one { public static void main(String arg[]) { Class.forname(oracle.jdbc.driver.OracleDriver)
} }
Type 4 driver.
Step 3
jdbc:odbc:dsn
// Create Connection object import java.sql.*; class one { public static void main(String arg[]) { Class.forname(sun.jdbc.odbc.JdbcOdbcDriver) Connection con=DriverManager.getConnection(database url,user,pwd); } }
jdbc:<sub protocol>://server_ip:port:database_name
jdbc:oracle:thin://localhost:1521:mydb
Step 4
// Create Connection object import java.sql.*; class one { public static void main(String arg[]) { Class.forname(sun.jdbc.odbc.JdbcOdbcDriver) Connection con=DriverManager.getConnection(database url,user,pwd); Statement stmt=con.createStatement(); }
Step 5
// Create Connection object import java.sql.*; class one { public static void main(String arg[]) { Class.forname(sun.jdbc.odbc.JdbcOdbcDriver) Connection con=DriverManager.getConnection(database url,user,pwd); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery(select * from emp where salary=100000); } }
ResultSet
rs
101
102 103 104
Mahesh
Vishal Naresh Dinesh
100000
100000 100000 100000
Noida
Delhi Delhi Banglore
Step 5
Move cursor to first row and move untill there is record in result set.
// traverse result set id from current record. Integer type Fetch import java.sql.*; class one { public static void main(String arg[]) { Class.forname(sun.jdbc.odbc.JdbcOdbcDriver) Connection con=DriverManager.getConnection(database url,user,pwd); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery(select * from emp where salary=100000); while(rs.next()) { System.out.println( Id + rs.getInt(ID)); System.out.println(Name+rs.getString(Name)); System.out.println(Salary + rs.getDouble(salary)); System.out.println( Addres+ rs.getString(address)); } }
JDBC URLs
Way of Identifying a database Appropriate Driver recognizes it and establishes a connection Allow driver writers to encode all necessary connection information
Driver Manager
DriverManager class maintains a list of Driver classes Driver classes need to register with the Driver Manager Registration is done automatically by the driver when it loaded Allows Keeping Track of Available Drivers
Connecting-Talking-Processing
A Connection Object represents a connection with a database A Connection Session includes Statements executed and Results got DriverManager.getConnection() - Standard way to establish connection The method takes a string containing a URL DriverManager tries to use each of the drivers in the order of registration
Connecting-Talking-Processing
DriverManager tests the drivers by calling the Driver.connect The first driver that recognizes the URL makes the connection Mechanism for reading and writing data between Java and SQL JDBC define a set of generic SQL type identifiers Dynamic Data Access
Database Connectivity
Connect method executeQuery method CloseConnection method Middleware API
Middleware API
Problem
For every database we need different database API. Database api has same methods for interacting with Connect method database.
executeQuery method CloseConnection method
Middle API
API functions
Database dependant
Driver
API Functi on
Oracle Driver
Mysql Driver
BACK
try { Class.forname(sun.jdbc.odbc.JdbcOdbcDriver) Connection con=DriverManager.getConnection(jdbc:odbc:system_dsn,user,pw Statement stmt=con.createStatement(); String query=insert into emp value(108,harry,20000,banglore); stmt.executeUpdate(query); } catch(Exception e){e.printStackTrace();}
} }
Executing query
boolean execute :- This method used to execute any sql statement. On successful execution it will return true otherwise false.
ResultSet executeQuery :- This method used to execute any sql statement. This method used to fetch data from databse ie. Select command.
int executeUpdate :- This method used to execute any sql statement which update databse ie. Update, insert, delete . On execution it will return number of row updated or deleted from databse.
Inserting 10 rows
Statement stmt = con.createStatement();
String query=insert into emp values ( 109,mahesh,10000,ajmer); int row=stmt.executeUpdate(query); While loop 10 times Take values from user for id, name, salary and city. String query=insert into emp values ( +id+,+name+,+salary+,+city+); int rows=stmt.executeUpdate(query); End for while loop
Inserting 10 rows
PreparedStatement stmt = con.prepareStatement(insert into emp values ( ?,?,?,?)); stmt.setInt(1,109); stmt.setString(2,harry); stmt.setDouble(3,10000); stmt.setString(4,banglore); stmt.executeUpdate();
PreparedStatement
While loop 10 times Take values from user for id, name, salary and city. stmt.setInt(1,id); stmt.setString(2,name); stmt.setDouble(3,salary); stmt.setString(4,city); stmt.executeUpdate(); End for while loop
Statement
Every time query is executed all these four steps are executed.
1. Parse the query 2. Compile the query 3. Optimize query 4. Execute query
PreparedStatement
Select * from emp where salary=10000;
1. Parse the query 1-3 are executed once using preparedStatement. 2. Compile the query 3. Optimize query Query is executed again and again. 4. Execute query
JDBC
Transferring A to B 1000
Read amount from A Read amount from B If As amount greater than 1000
Deduct 1000 from As account Deposit 1000 in Bs account Send error msg not having sufficient money
Else
//transferring amount import java.sql.*; class one { public static void main(String arg[]) { Class.forname(sun.jdbc.odbc.JdbcOdbcDriver) Connection con=DriverManager.getConnection(database url,user,pwd); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery(select amount from account where id=A); ResultSet rs1=stmt.executeQuery(select amount from account where id=B); rs.next(); rs1.next(); double amountA=rs.getDouble(amount); double amountB=rs1.getDouble(amount); if(amountA>1000) { amountB=amountB+1000; amountA=amountA-1000; stmt.executeQuery(update account set amount=+amountB+ where id=B); stmt.executeQuery(update account set amount=+amountA+ where id=A); } else System.out.println(Account not having sufficient money);
Problem : Every query is committed in database. Solution: Query not committed until all queries get executed successfully.
How to solve
Con.setAutoCommit(false); Program code here
. Con.commit();
//transferring amount import java.sql.*; class one { public static void main(String arg[]) { Class.forname(sun.jdbc.odbc.JdbcOdbcDriver) Connection con=DriverManager.getConnection(database url,user,pwd); con.setAutoCommit(false); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery(select amount from account where id=A); ResultSet rs1=stmt.executeQuery(select amount from account where id=B); rs.next(); rs1.next(); double amountA=rs.getDouble(amount); double amountB=rs1.getDouble(amount); if(amountA>1000) { amountB=amountB+1000; amountA=amountA-1000; stmt.executeQuery(update account set amount=+amountB+ where id=B); stmt.executeQuery(update account set amount=+amountA+ where id=A); con.commit(); } else System.out.println(Account not having sufficient money);
//transferring amount import java.sql.*; class one { public static void main(String arg[]) { Class.forname(sun.jdbc.odbc.JdbcOdbcDriver) Connection con=DriverManager.getConnection(database url,user,pwd); con.setAutoCommit(false); Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery(select amount from account where id=A); ResultSet rs1=stmt.executeQuery(select amount from account where id=B); rs.next(); rs1.next(); double amountA=rs.getDouble(amount); double amountB=rs1.getDouble(amount); amountB=amountB+1000; amountA=amountA-1000; stmt.executeQuery(update account set amount=+amountB+ where id=B); stmt.executeQuery(update account set amount=+amountA+ where id=A); if(amountA>1000) con.commit(); else con.rollback();
Transaction
1. Deduct from As account 1000 2. Deposit in Bs account 1000
Transaction properties-ACID
Atomicity : either all operations get executed otherwise none of them.
Consistency : Database will be in consistent state after transaction. example: for previous example Total of A+B will be same before and after transaction. Isolation : Transaction will execute in isolation, transaction wont get affected by other transactions. Transaction in intermediate state is not visible to other transaction. Durablitity: once transaction is successfully executed, transaction will persist or not to be undone.