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

Unit 2_JDBC

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 114

JDBC Programming

Chapter 2
By: B.U.Gadhia
Introduction
•JDBC (Java Database connectivity) is nothing but a Java API (Application
programming Interface)

•The function of this Java API is to document a standard framework for dealing with
data which may be tabular and generally relational data.

•The role of JDBC is just to act like a wrapper to let us feed SQL requests to the server

•What does JDBC do?

•The first one is to establish a connection with a database


•The second one is to send SQL statements
•And the last one is to process the results
JDBC vs. ODBC
•ODBC is not appropriate for direct use from Java because it uses a C interface. A number of
drawbacks have been found in the calls from Java to native C code in the security
implementation, robustness, and automatic portability of application

•It would not be desirable for a literal translation of the ODBC API into a Java API. Example, Java
has no pointer and ODBC makes copious use of them.

•ODBC is hard to learn. It is seen that in ODBC, simple and advanced features are mixed together,
and it has complex option for simple queries. On the other hand, JDBC was designed to keep
simple things simpler, while allowing more advanced capabilities as and when required

•The ODBC driver manager and drives must be manually installed on every client machine, when
ODBC is used. Although JDBC driver is written completely in Java, JDBC code is automatically
installable, portable and secure on all Java platforms from network computer to mainframes
JDBC Component
Driver Manager It load the database drivers and manages connection between the
application and the driver

Driver It translates API calls into operation for a specific data source

Connection It is a session between an application and a database

Statement It is an SQL statement to perform a query or update operation

MetaData It gives information about returned data, the database and the driver

ResultSet It is the logical set of columns and rows of data returned by executing
a statement
General Architecture

•What design pattern is implied


in this architecture?
•What does it buy for us?
•Why is this architecture also
multi-tiered?

5
6
Exploring JDBC Drivers
•Type-1 Driver
•Type-2 Driver
•Type-3 Driver
•Tpe-4 Driver
Type-1 Driver
Type-2 Driver
Type-3 Driver
Type-4 Driver
Basic steps to use
a database in Java
1.Establish a connection
2.Create JDBC Statements
3.Execute SQL Statements
4.GET ResultSet
5.Close connections

12
1. Establish a connection
•import java.sql.*;
•Load the vendor specific driver
–Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

•Make the connection Dynamically loads a driver class, for


Oracle database

–Connection con =
DriverManager.getConnection("jdbc:odbc:CITY_MASTER");
•What do you think this statement does?
•Establishes connection to database by obtaining
•a Connection object

13
2. Create JDBC statement(s)
•Statement stmt = con.createStatement() ;
•Creates a Statement object for sending SQL statements to the
database

14
Executing SQL Statements
•String Query= "select * from City_Master";

15
Get ResultSet
String Query= "select * from City_Master";

ResultSet rs = Stmt.executeQuery(Query);
//What does this statement do?

while (rs.next()) {

System.out.print(" ID : "+rs.getString(1)); //1st column of Table from Table


System.out.print(" CITY_CODE: "+rs.getString(2)); //2nd column of Table
System.out.print(" CITY_NAME "+rs.getString(3)); //3rd column of Table
System.out.println(" CITY_STATE: "+rs.getString(4)); //4th column of Table

16
Close connection
•stmt.close();
•con.close();

17
Step-1 Create new Blank database
Step-2 Make Table in database
Step-3
•Go to Control panel-> Administrative tools
Step-4 Select MS Access Database
Step-5 Select MS Access Driver
Step-6 Choose directories and
select database
Step-7
Create Database
Change Database
Create Table and insert Records
Display Table
C:\Users\Admin\.m2\repository\mysql\mysql-connector-
java\5.1.22\mysql-connector-java-5.1.22.jar
JDBC Example(Linux-MySql)
import java.sql.*;
public class Mysqldemo1
{
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver is loaded");
Connection c =
DriverManager.getConnection("jdbc:mysql://localhost:3306/city_master",
"root","123456");
System.out.println("Connection created");
Statement s = c.createStatement();
ResultSet rs = s.executeQuery("select * from city");
System.out.println("ID\t CITY_CODE\t City_NAME\t CITY_STATE");

while(rs.next()) // Retrieve data from ResultSet


{

System.out.println(rs.getString(1)+"\t"+rs.getString(2)+"\t"+rs.getString(3 )+"\t“
+rs.getString(4));

}
catch(Exception e)
{
System.out.println("Exception : " +e);
}
}
}
OUTPUT
JDBC Program(Windows - ODBC)
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class JDBCExample


{
public static void main(String[] args)
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Load Driver
Connection con = DriverManager.getConnection("jdbc:odbc:CITY_MASTER");
//Create Connection with Data Source Name : CITY_MASTER
Statement s = con.createStatement(); // Create Statement
String query = "select * from CITY_MASTER"; // Create Query
s.execute(query); // Execute Query
ResultSet rs = s.getResultSet(); //return the data from Statement into ResultSet
while(rs.next()) // Retrieve data from ResultSet
{
System.out.print(" ID : "+rs.getString(1)); //1st column of Table from database
System.out.print(" CITY_CODE: "+rs.getString(2)); //2nd column of Table
System.out.print(" CITY_NAME "+rs.getString(3)); //3rd column of Table
System.out.println(" CITY_STATE: "+rs.getString(4)); //4th column of Table
}
s.close();
con.close();
}
catch (Exception e)
{
System.out.println("Exception : "+e);
}
}
}
Output
Java.Sql package
•Connection Management
•Database Access
•Data Types
•Database Metadata
•Exceptions and warnings
Connection Management
Java.sql.Connection Creates connection with specific
database
Java.sql.Driver Create and register an instance of a
driver with driver manager

Java.sql.DriverManager Provides functionality to manage


database drivers

Database Access
Java.sql.Statement Executes Sql statements
Java.sql.PreparedStatement Executes parameterized sql statements

Java.sql.CallableStatement Executes Stored Procedures


Data Types
Java.sql.Array
Java.sql.Blob Blob-Binary Large Object
Java.sql.Clob Clob-Character Large Object
Java.sql.Date
Java.sql.Nclob NClob-National character large object

Database Metadata
Java.sql.DatabaseMetadata Obtains database features
Java.sql.ParameterMetadata
Java.sql.Resultsetmetadata Provides methods to access metadata of
result set
Exceptions and Warnings
Java.sql.BatchUpdateExceptions Updates Batches

Java.sql.DataTruncation Identifies data truncation


java.sql.Exception Represents all JDBC-related exception
conditions.
INSERT Query

import java.sql.*;
public class Mysqldemo1
{
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Driver is loaded");
Connection c =
DriverManager.getConnection("jdbc:mysql://localhost:3306/city_master","root","123456");
System.out.println("Connection created");
Statement s = c.createStatement();
String Query="insert into city values(5,011,'Mumbai','Maharashra')";
int count=s.executeUpdate(Query);
System.out.println("No. of Recodrds inserted:"+count);
}
catch(Exception e)
{ System.out.println("Exception : " +e);
}
}
}
Do your self
•String query = " SELECT * FROM CITY WHERE
State='"+state+"'";
Executing Query
•To execute a query, call an execute method
from Statement such as the following:
• execute: Returns true if the first object that the query returns is a ResultSet
object. Use this method if the query could return one or moreResultSet
objects. Retrieve the ResultSet objects returned from the query by repeatedly
calling Statement.getResutSet.
•executeQuery: Returns one ResultSet object.
•executeUpdate: Returns an integer representing the number of rows
affected by the SQL statement. Use this method if you are using
INSERT,DELETE, or UPDATE SQL statements.
Demo of Execute Query
String state=”Gujarat”;

Statement stmt = null;

String query = " SELECT * FROM CITY WHERE state='”+state+”'”;

try {
stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()) {

System.out.print(" ID : "+rs.getString(1)); //1st column of Table from Table


System.out.print(" CITY_CODE: "+rs.getString(2)); //2nd column of Table
System.out.print(" CITY_NAME "+rs.getString(3)); //3rd column of Table
System.out.println(" CITY_STATE: "+rs.getString(4)); //4th column of Table
}
stmt.close();
Demo of ExecuteUpdate
String population=”1705000”;
String cityName=”Mumbai”;
String State=”Maharashtra”;
Statement stmt = null;
.
.
.
stmt = connection.createStatement();
String sql = “UPDATE CITY_MASTER SET population=”+ population +” WHERE
NAME=”+ cityName +” AND PROVINCE=”+ province +””;

stmt.executeUpdate(sql);

stmt.close();
import java.sql.*;

public class JDBCExample {

static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";


static final String DB_URL = "jdbc:mysql://localhost/city_master";

static final String USER = "root";


static final String PASS = "123456";

public static void main(String[] args)


{
Connection conn = null;
Statement stmt = null;
try{

Class.forName("com.mysql.jdbc.Driver");

System.out.println("Connecting to a selected database...");


conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");

System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "UPDATE city SET CITY_CODE = 30 WHERE CITY_NAME='SURAT'";
stmt.executeUpdate(sql);
sql = "SELECT ID,CITY_CODE, CITY_NAME,CITY_STATE from city";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){

int ID= rs.getInt("ID");


int Code = rs.getInt("CITY_CODE");
String City_Name = rs.getString("CITY_NAME");
String City_State = rs.getString("CITY_STATE");

System.out.print("ID: " + id);


System.out.print(", CITY_CODE: " + age);
System.out.print(", CITY_NAME: " + first);
System.out.println(", CITY_STATE " + last);
}
rs.close();
}
}
catch(Exception e){
e.printStackTrace();
}
}//end try
}//end main
}//end JDBCExample
Update Output
import java.sql.*;
class FetchRecord ResultSet MetaData
{
public static void main(String args[])throws Exception{

Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/city_master",
"root","123456");
Statement
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCU
R_UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from city");

rs.relative(3);

System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));

rs.last();

System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
Delete Query
import java.sql.SQLException;
import java.sql.Statement;

public class DeleteExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/city_master";

static final String USER = "root";


static final String PASS = "123456";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
try{

Class.forName("com.mysql.jdbc.Driver");

System.out.println("Connecting to a selected database...");


conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");

System.out.println("Creating statement...");
stmt = conn.createStatement();

String sql = "DELETE FROM city WHERE ID = 4";


stmt.executeUpdate(sql);
sql = "SELECT ID,CITY_CODE, CITY_NAME,CITY_STATE from city";
ResultSet rs = stmt.executeQuery(sql);

while(rs.next()){

int id = rs.getInt("ID");
int age = rs.getInt("CITY_CODE");
String first = rs.getString("CITY_NAME");
String last = rs.getString("CITY_STATE");

System.out.print("ID: " + id);


System.out.print(", CITY_CODE: " + age);
System.out.print(", CITY_NAME: " + first);
System.out.println(", CITY_STATE " + last);
}
rs.close();

}
catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}

System.out.println("Goodbye!");
}
}
Delete Output
Difference between Statement & Prepared Statement
•There are four steps for the execution of query :

 Query is parsed,
Query is compile,
Query is optimized and
Query is executed.

In case of statement interface these four steps are performed ,each time
when query is submitted for execution.

But in case of prepared statement first three steps are performed


only once, when the query in initially submitted. Only the last step is
performed each time query is submitted(in subsequence submissions),

i.e if same query is submitted to be execute with different values


multiple times then prepared statement interface provides better
perfromance as compared to statement interface.
Difference between Statement & Prepared
Statement
•Execution of query is processed as follows.

– The connection object submits the SQL statement to database


–Database compiles the given statement
–Execution plan is prepared by the database
–Database returns the execution plan with unique id–Connection object

–The setXXX() methods are used to set the parameters of SQL–


–executeXXX () method is invoked to execute the SQL

–Database executes the execution plan with


supplied parameters
–Finally the result is sent to the java application
import java.sql.*;

public class PreparedStatementDemo1


Demo of Prepared Statement
{ int rows = ps.executeUpdate();
String query = "select * from City_Master"; // Create
public static void main(String args[]) { Query
try ps.executeQuery(query); // Execute Query
{ rs = ps.getResultSet();

Class.forName(" com.mysql.jdbc.Driver while(rs.next()) // Retrieve data from ResultSet


"); {
System.out.print(" ID : "+rs.getString(1));
Connection con = System.out.print(" CITY_CODE:
DriverManager.getConnection(" "+rs.getString(2));
jdbc:mysql://localhost:3306/city_master"," System.out.print(" CITY_NAME
root","123456 ");
"+rs.getString(3));
System.out.println(" CITY_STATE:
PreparedStatement ps= "+rs.getString(4));
con.prepareStatement("insert into }
City_Master values(?,?,?,?)");
} catch (Exception e) {
ResultSet rs = null; System.out.println(e);
}
ps.setInt(1, 4); }
ps.setInt(2, 36); }
ps.setString(3, “Jaipur");
ps.setString(4, “Rajasthan");
import java.sql.*;
import java.io.*;
public class Preparen {
public static void main(String args[])throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/city_master","root","1
23456");

PreparedStatement ps=con.prepareStatement("insert into city


values(?,?,?,?)");

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

do{
System.out.println("Enter Id:");
int id=Integer.parseInt(br.readLine());
System.out.println("Enter Code:");
int code=Integer.parseInt(br.readLine());
System.out.println("Enter Name");
String city_name=br.readLine();
System.out.println("Enter State");
String city_state=br.readLine();
ps.setInt(1,id);
ps.setInt(2,code);
ps.setString(3,city_name);
ps.setString(4,city_state);

int i=ps.executeUpdate();
System.out.println(i+" records affected");

System.out.println("Do you want to continue: y/n");


String s=br.readLine();
if(s.startsWith("n")){
break;
}

}while(true);

con.close();
}

}
Do by yourself
Write a program to update city name to
‘Ahmedabad’ where City Code=‘079’
using Prepared Statement.
//STEP 1. Import required packages
import java.sql.*;

public class JDBCExample {

public static void main(String[] args) {

try{

//STEP 2: Register JDBC driver

Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/city_master","root","123456");

PreparedStatement stmt = null;

//STEP 3: Open a connection

System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query


System.out.println("Creating statement...");

String sql = "UPDATE CITY_MASTER set city_name=? WHERE city_state=?";


stmt = conn.prepareStatement(sql);
//Bind values into the parameters.
stmt.setString(1, “Mumbai”); // This would set age
stmt.setString(2, “Maharashtra”); // This would set ID

int rows = stmt.executeUpdate();


System.out.println("Rows impacted : " + rows );

sql = "SELECT id, city_code, city_name, city_state FROM CITY_MASTER ";

ResultSet rs = stmt.executeQuery(sql);

//STEP 5: Extract data from result set


while(rs.next()){

int id = rs.getInt("id");
int city_code = rs.getInt("City_code");
String city_name = rs.getString("city_name"); OR
String city_state = rs.getString("city_state");

//Display values
System.out.print(" ID : "+rs.getString(1));
System.out.print(" CITY_CODE: "+rs.getString(2));
System.out.print(" CITY_NAME "+rs.getString(3));
System.out.println(" CITY_STATE: "+rs.getString(4));

}
//STEP 6: Clean-up environment

rs.close();
stmt.close();
conn.close();

}
catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}

}//end main
}//end JDBCExample
Definition: W. A. P To Display the information of of City Baroda,
Ahmedabad, Mumbai using “PreparedStatement Interface”.

import java.sql.*;

public class JdbcPreparedstatementExample


{

String driver = "sun.jdbc.odbc.JdbcOdbcDriver";


String connection = "jdbc:odbc:CITY_MASTER";

public static void main(String args[])


{

Connection con = null;


PreparedStatement pst = null;
ResultSet rs = null;

try {

Class.forName(driver);
con = DriverManager.getConnection(connection);
String sql =
"select * from City_Master where CITY_NAME " + "in(?,?,?)";
pst = con.prepareStatement(sql);

pst.setString(1, "Baroda");
pst.setString(2, "Ahmedabad");
pst.setString(3, "Mumbai");

rs = pst.executeQuery();
System.out.println("EmployeeID\tFirstName");
while (rs.next())
{
System.out.print(" "+rs.getString(1));
System.out.print("\t\t"+rs.getString(2));
System.out.println("\t\t"+rs.getString(3));
}

} catch (Exception e) {
System.out.println(e);
}
}
}
Output
CALLABLE
STATEMENT
Create Stored Procedure
import java.sql.*;

public class JDBCExample1 {


Callable Statement
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMPLOYEE";

static final String USER = "root";


static final String PASS = "123456";

public static void main(String[] args) {


Connection conn = null;
CallableStatement stmt = null;

try{

Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

System.out.println("Creating statement...");
String sql = "{call empproc2 (?, ?)}";
stmt = conn.prepareCall(sql);

stmt.setInt(1,1); // This would set ID as 1

stmt.registerOutParameter(2,Types.INTEGER);

System.out.println("Executing stored procedure..." );


stmt.execute();
System.out.println("Balance" +BALANCE);

stmt.close();
conn.close();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e){
e.printStackTrace();

}
}//end main
}//end JDBCExample
Table Creation
create table Emp
(
varchar(10) primary key,
name varchar(40) null,
city varchar(20),
salary int
);
insert into Emp values('a001','Ram Kumar','Noida',10000);
Using Callable Statement
CREATE PROCEDURE proc1()
BEGIN
SELECT * from Employee
FROM emp;
END; //

try {
clmt = con.prepareCall("{call proc2}");
ResultSet res = clmt.executeQuery();
while (res.next()) {
System.out.println(res.getString(1) + " " + res.getString(2)
+ " " + res.getString(3) + " " + res.getString(4));
}
} catch (Exception e) {
e.printStackTrace();
}
Using Callable Statement (IN Parameter)
CREATE PROCEDURE proc3(IN code1 varchar(10),IN name1 varchar(10))
BEGIN
insert into emp(code,name) values(code1,name1);
END; //

try {
clmt = con.prepareCall("{call proc3(?,?)}");
clmt.setString(1, code);
clmt.setString(2, name);
int i = clmt.executeUpdate();
if (i != 0)
System.out.println("Inserted successfully");
else
System.out.println("Not Inserted");
} catch (Exception e) {
}
Using Callable Statement (IN & Out Parameter)
CREATE PROCEDURE proc4(IN code1 varchar(10), OUT name1 varchar(10))
BEGIN
SELECT name from emp where code=code1
INTO name1;
END; //

try {
clmt = con.prepareCall("{call proc4(?,?)}");
clmt.setString(1, code);
clmt.registerOutParameter(2, Types.VARCHAR);
clmt.execute();
System.out.println(clmt.getString(2));
}

catch (Exception e) {
}
Store Image in to Database
(BLOB DataType)
import java.sql.*;
import java.io.*;
public class InsertImage {
public static void main(String[] args) {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/city_master","root","
123456");

PreparedStatement ps=con.prepareStatement("insert into imgtable values(?,?)");


ps.setString(1,“Bijal Gadhia");

FileInputStream fin=new
FileInputStream("/Home/NetBeansProjects/JavaApplication1/src/javaapplication1/pr
epared.png");
ps.setBinaryStream(2,fin,fin.available());
int i=ps.executeUpdate();
System.out.println(i+" records affected");

con.close();
}catch (Exception e) {e.printStackTrace();}
}
}
Methods of BLOB Interface
Methods Description

public InputStream getBinaryStream() Retrieves the BLOB Value

public byte[] getBytes(long pos, int Retrieves some portion of BLOB


length)
public long length() Returns the no. of Byte occupied by
BLOB value
public OutputStream Used to write BLOB value
getBinaryStream(long position )
public int setBytes( long pos, byte Writes Specified byte array in to
bytes[]) BLOB Object.
public void truncate() Truncate the BLOB Object
Describing CLOB Data type
import java.sql.*;
import java.util.*;
import java.io.*;

public class InsertEmployeeProfile {


public static void main(String s[]) throws Exception {
Driver d= (Driver) ( Class.forName( "com.mysql.jdbc.Driver ").newInstance());
Properties p=new Properties();
p.put("user",“root");
p.put("password",“123456");
Connection con=d.connect(" jdbc:mysql://localhost:3306/city_master ",p);
PreparedStatement ps= con.prepareStatement("insert into empprofiles values(?,?)");

ps.setInt(1,Integer.parseInt(s[0]));
File f=new File(s[1]);
FileReader fr= new FileReader(f);
ps.setCharacterStream(2,fr, (int)f.length());

int i=ps.executeUpdate();
System.out.println("Record inserted successfully , count : "+i);
con.close();
}//main
}//class
import java.sql.*;
Describing Array Data type
import java.util.*;

public class InsertEmpPassportDetails {


public static void main(String s[]) throws Exception {

Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/city_master","root","");

PreparedStatement ps = con.prepareStatement("insert into emppassportDetails


values(?,?,?)");

ps.setInt(1, 7934);
ps.setString(2, "12345A134");
String s1[] = {"v1", "v2", "v3", "v4", "v5"};
String visaNumbers = String.join(",", s1); // Convert array to comma-separated string
ps.setString(3, visaNumbers);
int i = ps.executeUpdate();
System.out.println("Row Inserted, count : " + i);
con.close();
}
}
Database Metadata

import java.sql.*;
class dbmd{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");

Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/city_master","root","123456");

DatabaseMetaData dbmd=con.getMetaData();

System.out.println("Driver Name: "+dbmd.getDriverName());


System.out.println("Driver Version: "+dbmd.getDriverVersion());
System.out.println("UserName: "+dbmd.getUserName());
System.out.println("Database Product Name: "+dbmd.getDatabaseProductName());
System.out.println("Database Product Version: "+dbmd.getDatabaseProductVersion());

con.close();

}catch(Exception e){ System.out.println(e);}

}
}
Output of Database Metadata
import java.sql.*;
class Rsmd ResultSet Metadata
{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");

Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/city_master","root","
123456");

PreparedStatement ps=con.prepareStatement("select * from city");


ResultSet rs=ps.executeQuery();

ResultSetMetaData rsmd=rs.getMetaData();

System.out.println("Total columns: "+rsmd.getColumnCount());


System.out.println("Table Name : "+rsmd.getTableName(1));
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(2));
System.out.println("Column Type Name of 1st column:
"+rsmd.getColumnTypeName(2));

con.close();

}catch(Exception e){ System.out.println(e);}


Output of ResultSet Metadata
ResultSet
Type of ResultSet:
–Default: TYPE_FORWARD_ONLY.
oResultSet.TYPE_FORWARD_ONLY: The cursor can only move forward in the
result set.
oResultSet.TYPE_SCROLL_INSENSITIVE
oResultSet.TYPE_SCROLL_SENSITIVE

Concurrency of ResultSet:
–Default: CONCUR_READ_ONLY.
oResultSet.CONCUR_READ_ONLY
oResultSet.CONCUR_UPDATABLE
Method Description
public boolean first() throws SQLException

public void last() throws SQLException

public boolean absolute(int row) throws SQLException

public boolean relative(int row) throws SQLException

public boolean previous() throws SQLException

public boolean next() throws SQLException

public int getRow() throws SQLException

public void moveToInsertRow() throws SQLException

public void moveToCurrentRow() throws SQLException


import java.sql.*;

public class ResultSetNavigationExample {


public static void main(String[] args) {
try {
// Establish connection
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username",
"password");

// Create a statement
Statement statement = connection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);

ResultSet resultSet = statement.executeQuery("SELECT * FROM city_master");

if (resultSet.first()) { displayCityInfo(resultSet); }

resultSet.last();
displayCityInfo(resultSet);

resultSet.absolute(3);
displayCityInfo(resultSet);

resultSet.relative(1);
displayCityInfo(resultSet);

resultSet.previous();
displayCityInfo(resultSet);
resultSet.next();
displayCityInfo(resultSet);

int currentRow = resultSet.getRow();


System.out.println("Current Row: " + currentRow);

// Move to the insert row


resultSet.moveToInsertRow();

// Move back to the current row


resultSet.moveToCurrentRow();

// Close connection
connection.close();
}
catch (SQLException e)
{
e.printStackTrace();
}
}

private static void displayCityInfo(ResultSet resultSet) throws SQLException {


int cityId = resultSet.getInt("city_id");
String cityName = resultSet.getString("city_name");
int population = resultSet.getInt(“city_state");

System.out.println("City ID: " + cityId + ", City Name: " + cityName + ", City_State : " + city_state);
}
}
Methods & Description :
• public void updateRow()
• Updates the current row by updating the corresponding row in the database.
• public void deleteRow()
• Deletes the current row from the database
• public void refreshRow()
• Refreshes the data in the result set to reflect any recent changes in the database.
• public void cancelRowUpdates()
• Cancels any updates made on the current row.
• public void insertRow()
• Inserts a row into the database. This method can only be invoked when the cursor
is pointing to the insert row.
import java.sql.*;
public class jdbcConn
{
public static void main(String[] args) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Load Driver
Connection con = DriverManager.getConnection("jdbc:odbc:CITY_MASTER");
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE) ;

String query = "select * from City_Master";


ResultSet rs = stmt.executeQuery(query);

rs.last();
System.out.println("No of rows in table="+rs.getRow());
rs.moveToInsertRow();

rs.updateInt("ID", 9);
rs.updateString("City_Code","055");
rs.updateString("City_Name", "SURAT");
rs.updateString("City_Name", "SURAT");
rs.updateString("City_State", "GUJARAT");

rs.insertRow();
System.out.println("Row added");
}
}
Output
Batch Updates
•Send Multiple updates
•Ex.
Statement st=con.createStatement();

st.addBatch(“insert into emp values (‘abc’) ”);


st.addBatch (“insert into emp_1 values (‘ def ’) ”);
st.addBatch (“insert into emp_2 values (‘ xyz’) ”);

Int [] updateCount= st.executeBatch();


try{
Class.forName("com.mysql.jdbc.Driver"); Demo of Batch Updates
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");

System.out.println("Creating statement...");
stmt = conn.createStatement();

stmt.addBatch("insert into EMPDETAILS(EMP_ID,EMP_CODE,EMP_NAME,SAL)


values(001,11,'BIJAL GADHIA',40000)");

stmt.addBatch("update EMPDETAILS set SAL=45000 where EMP_CODE=11");

stmt.addBatch("insert into EMPDETAILS(EMP_ID,EMP_CODE,EMP_NAME,SAL)


values(002,22,'POOJA SHAH',40000)");

stmt.addBatch("insert into EMPDETAILS(EMP_ID,EMP_CODE,EMP_NAME,SAL)


values(003,11,'PRACHI',40000)");
int[] counts=stmt.executeBatch();
System.out.println("Batch Executed Successfully");

}
catch(SQLException se){
se.printStackTrace();
}

}//end main
}//end JDBCExample
Transactions
JDBC allows SQL statements to be grouped together into a single transaction.

•con.setAutoCommit(false);

•Statement stmt = con.createStatement();

•stmt.executeUpdate("INSERT INTO .....” );

•con.rollback();

•stmt.executeUpdate("INSERT INTO ....." );

•con.commit();

•con.setAutoCommit(true);
import java.sql.*;
public class JdbcAutocommit
{
public static void main(String args[])
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Load Driver
Connection con = DriverManager.getConnection("jdbc:odbc:Cust_MASTER");
con.setAutoCommit(false);

Statement st = con.createStatement();
String sql = “Update customer set cust_name=“ABC ” where cust_id=123";
rs = st.executeQuery(sql);

con.Commit();

catch (Exception e)
{ System.out.println(e); } } }
try{

conn.setAutoCommit(false);

Statement stmt = conn.createStatement();

String SQL = "INSERT INTO Employees " + "VALUES (105, 20, 'Rita', 'Tez')";

stmt.executeUpdate(SQL);

String SQL = "INSERT IN Employees " + "VALUES (107, 22, 'Sita', 'Singh')";
stmt.executeUpdate(SQL);

conn.commit();

}
catch(SQLException se)
{
conn.rollback();
}
import java.sql.*; Demo of Transaction Management
import java.util.*;
import java.io.*;

public class TransfreAmount {


public static void main(String s[]) throws Exception {
Driver d= (Driver(
Class.forName("com.mysql.jdbc.Driver").newInstance());

Properties p=new Properties();


p.put("user","root");
p.put("password","123456");
Connection con=d.connect("jdbc:mysql://localhost/EMPLOYEE",p);
con.setAutoCommit(false);

String srcaccno=“1";
String destaccno="2";

PreparedStatement ps=con.prepareStatement("update BANK1 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);
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

You might also like