Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Java Week 15

The document provides an overview of JDBC (Java Database Connectivity) and its various driver architectures, including Type-1, Type-2, Type-3, and Type-4 drivers. It includes code examples demonstrating how to use JDBC for database operations such as executing queries, using PreparedStatements, and handling transactions. Additionally, it touches on the creation of database objects and the management of database connections.

Uploaded by

shitalshalini88
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java Week 15

The document provides an overview of JDBC (Java Database Connectivity) and its various driver architectures, including Type-1, Type-2, Type-3, and Type-4 drivers. It includes code examples demonstrating how to use JDBC for database operations such as executing queries, using PreparedStatements, and handling transactions. Additionally, it touches on the creation of database objects and the management of database connections.

Uploaded by

shitalshalini88
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45



JAIN
DEEMED-TO-BE UNIVERSIT Y



JAIN
DEEMED-TO-BE UNIVERSIT Y


JAIN
DEEMED-TO-BE UNIVERSIT Y

HTML_ Response HTML_


Java
or Response or
Server
JSP JSP
Pages Page
Page
Request Servlets
Servlets use data
models and query
files to access
JDBC resources
JDBC calls EJBs through EJBs andk
JDBC bowset calls

JDBC JDBC
Resources Resources

JDBC
Resources
JAIN
DEEMED-TO-BE UNIVERSIT Y
JAIN
DEEMED-TO-BE UNIVERSIT Y

Native DBMS
Specific Call
JDBC Native ODBC
Call Call

SP API Oracle

ODBC API
JDBC API JDBC-
Java SQL
ODBC ODBC SP API
App
Bridge Driver Server
Driver

SP API Sybase


JAIN
DEEMED-TO-BE UNIVERSIT Y

Type-2 Driver Architecture

Client Side
Native
Call
JDBC Type-2
Call Driver

DBMS Specific
Native API
Java JDBC API
Database
App
Server
JAIN
DEEMED-TO-BE UNIVERSIT Y

Type-3 Driver Architecture


Server
Native DBMS
Client Side Specific

JDBC
Call Middleware
Type-3
Server SP API Oracle
Driver

Java JDBC
Server SP API SQL
App Driver Server

SP API Sybase
JAIN
DEEMED-TO-BE UNIVERSIT Y


JAIN
DEEMED-TO-BE UNIVERSIT Y

Client Side
DB
Specific
JDBC Type-4
Call Driver
DBMS Specific
Java Network Protocol
JDBC API
App Database
Server


JAIN
DEEMED-TO-BE UNIVERSIT Y


JAIN
DEEMED-TO-BE UNIVERSIT Y
JAIN
DEEMED-TO-BE UNIVERSIT Y
JAIN
DEEMED-TO-BE UNIVERSIT Y

PreparedStatement

ResultSet


JAIN
DEEMED-TO-BE UNIVERSIT Y
JAIN
DEEMED-TO-BE UNIVERSIT Y
JAIN
DEEMED-TO-BE UNIVERSIT Y

jdbc: <sub protocol> : <info>


JAIN
DEEMED-TO-BE UNIVERSIT Y

For Type-1 driver, i.e., JDBC-ODBC Bridge Driver, the JDBC URL is:
jdbc: odbc: SuchitaDSN.
For Oracle Type-2 driver:
String dbName = "kogent";
String oracleURL = "jdbc:oracle:oci8:@" + dbName;
//oracleURL = "jdbc:oracle:oci8:@kogent"
For Oracle Type-4 driver:
String host = "localhost";
String dbName = "kogent";
int port = 1521;
String oracleURL = "jdbc:oracle:thin:@" + host + ":" + port + ":" +
dbName;
//oracleURL = "jdbc:oracle:thin:@192.168.1.123:1521:XE""

Statement stmt = connection.createStatement();

//Using executeQuery()
String query = "SELECT col1, col2, col3 FROM table_name";
ResultSet results = stmt.executeQuery(query);
//Using executeUpdate()
String query= "INSERT into table_name values (value1, value2, …, value
n)";
int count = stmt.executeUpdate(query);

while(results.next())
{
JAIN
DEEMED-TO-BE UNIVERSIT Y

System.out.println(results.getString(1) + " " +


results.getString(2) + " " +
results.getString(3));
}

con.close();
JAIN
DEEMED-TO-BE UNIVERSIT Y
JAIN
DEEMED-TO-BE UNIVERSIT Y

Connection con = DriverManager.getConnection (url, "username",


"password");
Statement stmt = con.createStatement();


JAIN
DEEMED-TO-BE UNIVERSIT Y

JVM Database

Java Application JDBC Driver 2 3) Compile the SQL Statement

st 4) Prepare an execution plan


to execute the SQL Statement
1
executeXX... 5) Execute the compiled
Statement
SQL Statement’s plan
8 response Object

7 6) Cache the results into


buffer (CURSOR) if the
SQL Statement is
data Retrieval Statement


JAIN
DEEMED-TO-BE UNIVERSIT Y


JAIN
DEEMED-TO-BE UNIVERSIT Y


JAIN
DEEMED-TO-BE UNIVERSIT Y

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con= DriverManager.getConnection (url, "user", "password");
String query="insert into mytable values (?,?,?)";
//Step1: Get PreparedStatement object
PreparedStatement ps=con.prepareStatement (query);

//Step2: setting values for the parameters


ps.setString(1,"abc1");
JAIN
DEEMED-TO-BE UNIVERSIT Y

ps.setInt(2,38);
ps.setDouble(3,158.75);

//Step3: Executing the SQL statements


int n = ps.executeUpdate(); // n is the number of rows or tables
that are being updated

import java.sql.*;
public class PreparedStatementEx1 {
public static void main(String s[]) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
Connection con= DriverManager.getConnection (
"jdbc:oracle:thin:@localhost:1521:XE","scott","tiger");

String query="insert into mytable values (?,?,?)";


//Step1: Get PreparedStatement
PreparedStatement ps=con.prepareStatement (query);
//Step2: set parameters
ps.setString(1,"abc1");
ps.setInt(2,38);
ps.setDouble(3,158.75);
//Step3: execute the query
int i=ps.executeUpdate();
System.out.println("record inserted count:"+i);
//To execute the query once again
ps.setString(1,"abc2");
ps.setInt(2,39);
ps.setDouble(3,158.75);
i=ps.executeUpdate();
System.out.println("query executed for the second time count:
"+i);
con.close();
}//main
}//class

record inserted count: 1


query executed for the second time count: 1
JAIN
DEEMED-TO-BE UNIVERSIT Y


JAIN
DEEMED-TO-BE UNIVERSIT Y


JAIN
DEEMED-TO-BE UNIVERSIT Y

createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_
ONLY);
prepareStatement(query, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.
CONCUR_READ_ONLY);
JAIN
DEEMED-TO-BE UNIVERSIT Y

import java.sql.*;
import java.util.*;
import java.io.*;
public class ScrollableRSEx1 {
public static void main(String s[]) throws Exception {
Driver d= (Driver) (Class.forName(
"oracle.jdbc.driver.OracleDriver").newInstance());
Properties p=new Properties ();
p.put("user","scott");
p.put("password","tiger");
Connection con=d.connect("jdbc:oracle:thin:@
localhost:1521:XE",p);
Statement st= con.createStatement (
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);

String query="select * from emp where deptno=3";


ResultSet rs= st.executeQuery(query);
//Now the cursor of ResultSet will at beforeFirst & the result
set produced is scrollable
System.out.println("EmpNo\tName");
while (rs.next()) {
System.out.print(rs.getInt(1)+"\t");
System.out.println(rs.getString(2));
}//while
//Now the cursor of ResultSet will at afterLast
System.out.println(
"Reading Data, moving the cursor in backward direction\n");
while (rs.previous()){
System.out.print(rs.getInt(1)+"\t");
System.out.println(rs.getString(2));
}//while
con.close();
}//main
}//class
JAIN
DEEMED-TO-BE UNIVERSIT Y

import java.util.*;
import java.io.*;
import java.sql.*;
public class ScrollableRSEx2 {
public static void main(String s[]) throws Exception {
Driver d= (Driver)(Class.forName(
"oracle.jdbc.driver.OracleDriver").newInstance());
Properties p=new Properties ();
p.put("user","scott");
p.put("password","tiger");
Connection con=d.connect
("jdbc:oracle:thin:@192.168.1.123:1521:XE ",p);
PreparedStatement ps= con.prepareStatement ("select * from
emp",
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet rs=ps.executeQuery();
System.out.println ("Index\tEmpNo\tName");
int i=1;
while (rs.next()){
System.out.print ((i++)+"\t");
System.out.print (rs.getInt(1)+"\t");
System.out.println (rs.getString(2));
}//while
System.out.println ();
//Now the cursor will be at afterLast
//From this point to move the cursor to 3rd record
rs.absolute(3);
System.out.println ("3rd record EmpNo : "+rs.getInt(1));
/*
To move the cursor to first record we can use
rs.first(); or with reference to the current row we can use
*/
rs.relative(-2);
System.out.println ("1st record EmpNo: "+rs.getInt(1));
JAIN
DEEMED-TO-BE UNIVERSIT Y

/*
To move the cursor to last record use rs.last () or with reference to the
current row we can use
*/
rs.afterLast (); //this moves the cursor to afterLast
rs.previous ();
//moves the cursor backward by one row (which in this case moves the
cursor last row
System.out.println ("last record EmpNo: "+ rs.getInt (1));
con.close ();
}//main
}//class
JAIN
DEEMED-TO-BE UNIVERSIT Y


JAIN
DEEMED-TO-BE UNIVERSIT Y


JAIN
DEEMED-TO-BE UNIVERSIT Y

// Assume con is a Connection object


con.setAutoCommit(false);

Statement s = conn.createStatement();
int rows = s.executeUpdate("INSERT INTO TABLE1 (COLUMN1) VALUES " +
"('FIRST')");
// set Savepoint
Savepoint sp = conn.setSavepoint("SAVEPOINT_1");
JAIN
DEEMED-TO-BE UNIVERSIT Y

rows = s.executeUpdate("INSERT INTO TABLE1 (COLUMN1) " +


"VALUES ('SECOND')");
...
conn.rollback(sp);
...
conn.commit();

package com.jdbc;
import java.sql.*;
import java.util.*;
import java.io.*;
/**
* @author Suchita
*/
public class TransferAmount {
public static void main(String s[]) throws Exception {
Driver d= (Driver) (Class.forName(
"oracle.jdbc.driver.OracleDriver").newInstance());
Properties p=new Properties();
p.put("user","scott");
p.put("password","tiger");
Connection con=d.
connect("jdbc:oracle:thin:@192.168.1.123:1521:XE",p);
con.setAutoCommit(false);
String srcaccno=s[0];
String destaccno=s[1];
PreparedStatement ps= con.prepareStatement(
"update bank set bal=bal+? where accno=?");
ps.setInt(1,500);
ps.setString(2,destaccno);
int i=ps.executeUpdate();
ps.setInt(1,-500);
ps.setString(2,srcaccno);
JAIN
DEEMED-TO-BE UNIVERSIT Y

int j=ps.executeUpdate();
if (i==1&&j==1){
con.commit();
System.out.println("Amount transfered");
con.close();
return;
}
con.rollback();
System.out.println("Cannot transfer the amount");
con.close();
}//main
}//class

Create table bank (accno varchar2(20), bal number (10, 2));


Insert into bank values ('101', 10000);
Insert into bank values ('102', 10000);
JAIN
DEEMED-TO-BE UNIVERSIT Y


JAIN
DEEMED-TO-BE UNIVERSIT Y
JAIN
DEEMED-TO-BE UNIVERSIT Y

create type <name> as OBJECT (<variable name> <type>, ...);

CREATE TYPE empaddress AS OBJECT (


flatno NUMBER,
street VARCHAR2(20),
city VARCHAR2(15),
state VARCHAR2(10),
pincode NUMBER
);
JAIN
DEEMED-TO-BE UNIVERSIT Y
JAIN DEEMED-TO-BE UNIVERSIT Y

create Type <type name> as VARRAY(<length>) of <type>

Conclusion


JAIN
DEEMED-TO-BE UNIVERSIT Y


JAINDEEMED-TO-BE UNIVERSIT Y

@

import java.sql.*;
public class JDBCExample {
static String url = "jdbc:mysql://localhost:3306/
testdb?useSSL=false";
JAIN
DEEMED-TO-BE UNIVERSIT Y

static String user = "root";


static String password = "Deepak@123";
public static void main(String[] args) {
String student = "John";
String address = "Delhi";
String sql = "INSERT INTO Students(Name, Address) VALUES(?,
?)";
try (Connection con = DriverManager.getConnection(url, user,
password);
PreparedStatement pst = con.prepareStatement(sql)) {
pst.setString(1, student);
pst.setString(2, address);
pst.executeUpdate();
System.out.println("A new student has been inserted");

} catch (SQLException ex) {


System.out.println(ex.toString());
}

JDBCExample.show();
}
static void show()
{
ResultSet rs;
String name, address;
String sql1 = "Select Name, Age from Students where Name=?";
try(Connection con1 = DriverManager.getConnection(url, user,
password);
PreparedStatement pst1 = con1.prepareStatement(sql1)) {
pst1.setString(1,"John");
rs = pst1.executeQuery();
while (rs.next()) {
name = rs.getString(1);
address = rs.getString(2);
System.out.println("Student name = " + name + "Student address
= " + address);
}
} catch (SQLException ex) {
System.out.println(ex.toString());
}
}
}

You might also like