Java Database Connectivity (2)
Java Database Connectivity (2)
===============================
where can you store the data?
1. variable
2. file
3. database
where can you store the data perminently?
1. file
2. database
what are the components of a data storage?
1. data
2. medium
3. storage
what data indicates?
what to persist
what medium indicates?
how to persist
what storage indicates?
where to persist
In Java programs, where the data exist?
1. in variables
2. in objects
To store/read the data in a file, which Java concepts are used?
output streams & input streams
serialization & de-serialization
To store/read the data in a database, which Java technology is used?
JDBC
what is JDBC?
JDBC is an API(Application Programming Interface).
JDBC API consists a set of pre-defined classes and
interfaces, which are used by the Java programs to
interact with a Database and can store the data or
can retrieve the data.
JDBC Driver:
JDBC driver is a software component which connects
Java applications with the databases and transfers
the data between the program and a database.
Mostly database vendors provides the JDBC Driver
softwares.
The JDBC driver softwares, are divided into 4 types.
1. Type 1(JDBC ODBC Bridge Driver)
2. Type 2 (Native API Partially Java Driver)
3. Type 3 (Net Protocol Pure Java Driver)
4. Type 4(Native Protocol Pure Java Driver)
Note:
MySQL shell, is a command line application to connect
with MySQL server.
MySQL workbench is a graphical user application to
connect with MySQL server.
MySQL Workbench:
Goto windows search, type MySQL Workbench and
open the application.
click on the local instance button enter the
password ok.
click on schemas tab at left side
type the below query in Query editor at right side, to
create a new database called test.
1. launch Eclipse
2. create a new Java project in eclipse.
(project: CreateTableProgram)
3. In src folder, delete module-info.java
4. create a new class in src folder, with package name
com.ashokit.jdbc and class name CreateTable.
5. write the below program code.
package com.ashokit.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
stmt.executeUpdate(insert_query_1);
stmt.executeUpdate(insert_query_2);
stmt.executeUpdate(insert_query_3);
System.out.println("insert queries are executed.");
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
//step-6
rs.close();
stmt.close();
conn.close();
System.out.println("connection is closed");
PreparedStatement in jdbc:
PreparedStatement ps = conn.prepareStatement(sqlQuery);
package com.ashokit.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
conn = DriverManager.getConnection(URL,
USERNAME, PASSWORD);
System.out.println("connection is opened");
insertData();
conn.close();
System.out.println("connection is closed");
}
//create PreparedStatement
PreparedStatement ps =
conn.prepareStatement(sqlQuery);
//create Scanner
Scanner scan = new Scanner(System.in);
//insert 3 records
for ( int i = 1; i <= 3; i++ ) {
System.out.println("enter sid : ");
int sid = scan.nextInt();
scan.nextLine();
}
ps.close();
scan.close();
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
conn = DriverManager.getConnection(URL,
USERNAME, PASSWORD);
System.out.println("connection is opened");
insertImage();
conn.close();
System.out.println("connection is closed");
//execute
int count = ps.executeUpdate();
System.out.println(count + " : row inserted");
ps.close();
}
}
CallableStatement:
package com.ashokit.jdbc;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Types;
import java.util.Scanner;
try {
conn = DriverManager.getConnection(URL,
USERNAME, PASSWORD);
System.out.println("connection is opened");
calculateBonus(conn);
}
catch(Exception ex) {
System.out.println(ex);
}
finally {
try {
if( conn!= null ) {
conn.close();
System.out.println("connection is
closed");
}
}
catch(Exception ex) {
System.out.println(ex);
}
}
}
}
creating a procedure:
A procedure doesn’t return a value explicitly, but it can store
the values in out/inout parameters.
A procedure parameters can have any of 3 parameter
modes.
in – input
out – output
inout – input and output
the below procedure takes deptno as input and selects
the name and location of that department, stores them in
out parameters.
CREATE PROCEDURE `dept_procedure`(in dno int, out
deptname varchar(20), out deptloc varchar(20))
BEGIN
select dname into deptname from dept where deptno =
dno;
select loc into deptloc from dept where deptno = dno;
END
package com.ashokit.jdbc;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Types;
import java.util.Scanner;
try {
conn = DriverManager.getConnection(URL,
USERNAME, PASSWORD);
System.out.println("connection is opened");
findDeptDetails(conn);
}
catch(Exception ex) {
System.out.println(ex);
}
finally {
try {
if( conn!= null ) {
conn.close();
System.out.println("connection is
closed");
}
}
catch(Exception ex) {
System.out.println(ex);
}
}
}
}
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
try {
conn = DriverManager.getConnection(URL,
USERNAME, PASSWORD);
System.out.println("connection is opened");
findMetaData(conn);
}
catch(Exception ex) {
System.out.println(ex);
}
finally {
try {
if( conn!= null ) {
conn.close();
System.out.println("connection is
closed");
}
}
catch(Exception ex) {
System.out.println(ex);
}
}
ResultSet rs = stmt.executeQuery(str);
}
catch(Exception ex) {
System.out.println(ex);
}
Jdbc Transaction:
A transaction is a group of/sequence of operations, that
are executed as a single unit of work.
A transaction follow a principle that either all operations
of the unit are executed or none of them are executed.
A transaction can be successful or failed.
For example, when you make online purchase, the
operations like deducting product from the inventroy,
charging the customer, and generating the order.
Suppose, in the midway like payment declined error
occurs then the operations of the transaction are rolled
back, and the transaction is ended with status failed.
By default, each query is executed as a separate
transaction from the jdbc program.
If you want to execute multiple queries as a single
transaction from the jdbc program then you have to
apply Jdbc Transaction mechanism.
We have to use the below methods.
1. setAutoCommit(boolean) : The parameter is true, by
default.
we have to disable the auto commit mode, by providing
false as parameter.
conn.setAutoCommit(false);
package com.ashokit.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
try {
conn = DriverManager.getConnection(URL,
USERNAME, PASSWORD);
System.out.println("connection is opened");
transferMoney(conn);
} catch(Exception ex) {
System.out.println(ex);
}
finally {
try {
if( conn != null) {
conn.close();
System.out.println("connection is closed");
}
} catch(SQLException ex) {
System.out.println(ex);
}
}
private static void transferMoney(Connection conn) {
PreparedStatement ps1 = null;
PreparedStatement ps2 = null;
try {
Scanner scan = new Scanner(System.in);
System.out.println("enter from account ");
int fromAccount = scan.nextInt();
System.out.println("enter to account ");
int toAccount = scan.nextInt();
System.out.println("enter amount to transfer");
double amount = scan.nextDouble();
//Disable auto commit mode
conn.setAutoCommit(false);
ps1 = conn.prepareStatement(query1);
ps2 = conn.prepareStatement(query2);
ps1.setDouble(1, amount);
ps1.setInt(2, fromAccount);
ps2.setDouble(1, amount);
ps2.setInt(2, toAccount);
ps1.executeUpdate();
ps2.executeUpdate();
}
}
Scrollable ResultSet :
---------------------
By default, when we create a ResultSet object,
it is a forward only result set.
It means, the cursor can be moved only in the forward
direction.
If you want to move the cursor in forward and backward
direction also, then you have to create a scrollable result
set object.
while creating a statement object, we need to pass two
parameters called type and mode.
Connection pooling:
Suppose, if our application is a server-side application
and if it is creating a new connection and destroying
connection for each request, the problems are,
1. performance: opening a new connection is time-
consuming.
2. resource problem: if many clients/users are making
request at a time, then the application has to open
a new connection for each request. It leads to out
of memory errors.
The solution is connection pooling technique.
In this technique, a group/limit of connections are
opened to a database and stored in memory area called
pool.
The same connections are re-used for all the requests by
the application.
How connection pool works?
A connection pool is created mostly by server admin at
the application startup.
when a user sends request, the application borrows the
connection from the pool.
After executing the database operations/queries, instead
of closing the connection, the application returns the
connection back to the pool.
if all the connections are busy/in use, then the new
requests will be put on hold and when a connection
comes back to the pool, it is served for the waiting
request.
Who is DataSource?
DataSource is an interface from javax.sql package.
A Java application can obtain a connection with a
Database, using either DriverManager class or
DataSource interface.
DriverManager can provide direct connection with a
database, but it can’t provide a connection from the pool.
DataSource can provide a connection pool. It means, Java
application uses DataSource object to borrow the
connection from a pool.
==================================
==============