[go: up one dir, main page]

0% found this document useful (0 votes)
39 views18 pages

JDBC

JDBC (Java Database Connectivity) is a Java standard API that provides a database-independent interface for connecting Java applications to relational databases. It includes components such as DriverManager, Connection, Statement, and ResultSet, and supports various types of JDBC drivers for different database interactions. The document outlines the architecture, components, and programming steps required to establish a JDBC connection and execute SQL statements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views18 pages

JDBC

JDBC (Java Database Connectivity) is a Java standard API that provides a database-independent interface for connecting Java applications to relational databases. It includes components such as DriverManager, Connection, Statement, and ResultSet, and supports various types of JDBC drivers for different database interactions. The document outlines the architecture, components, and programming steps required to establish a JDBC connection and execute SQL statements.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Unit I: JDBC

● JDBC is a Java standard that provides the interface for connecting programs in Java to
relational databases.
● The JDBC standard is defined by Sun Microsystems and implemented through the standard
java.sql interfaces.
● JDBC stands for Java Database Connectivity, which is a standard Java API for database
independent connectivity between the Java programming language and a wide range of
databases.
● The JDBC library includes APIs for each of the tasks:
Making a connection to a database
Creating SQL or MySQL statements
Executing that SQL or MySQL queries in the database
Viewing & Modifying the resulting records
● JDBC API is a Java API that can access any kind of tabular data, especially data stored in a
RDB.

Design of JDBC
● It has been designed to provide database independence for developers.

● JDBC is designed to provide a database-neutral API for accessing relational databases from
different vendors.
● JDBC has been designed in such a way that the database application can use the same
methods to access data regardless of the underlying database product.
● JDBC was developed to work with the most common type of database: the relational
database.
● JDBC consists of two layers: JDBC API and JDBC Driver Manager API.

● The JDBC API is the top layer and is the programming interface in Java to SQL.

● The JDBC API communicates with the JDBC Driver Manager API, sending it various SQL
statements.
● The manager communicates with the third party that actually connect to the database and
return the information from the query.

JDBC Architecture:
● The JDBC API supports both two-tier and three-tier processing models for database
access but in general JDBC Architecture consists of two layers:
JDBC API: provides the application-to-JDBC Manager connection.
JDBC Driver Manager API: supports the JDBC Manager-to-Driver Connection.
● JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases(use more than one kind of processor or cores).
● JDBC driver manager ensures that the correct driver is used to access each data source.

● The driver manager is capable of supporting multiple concurrent drivers connected to


multiple heterogeneous databases.

JDBC Components:
Driver Manager: This class manages a list of database drivers.
Matches connection requests from the java application with the proper database driver using
communication sub protocol.
The first driver that recognizes a certain subprotocol under JDBC will be used to establish a
database connection.

Driver: This interface handles the communications with the database server. You will interact
directly with Driver objects very rarely. Instead, you use Driver Manager objects, which manages
objects of this type.

Connection : This interface has methods for contacting a database.


The connection object represents communication context, i.e., all communication with database is
through connection object only.

Statement : It is used to submit the SQL statements to the database.

ResultSet: These objects hold data retrieved from a database after you execute an SQL query using
Statement objects.

SQLException: This class handles any errors that occur in a database application.
JDBC configuration
# JDBC Driver: It implements defined interfaces in the JDBC API for interacting with your
database server.
For example, using JDBC drivers you can open database connections and interact with it by
sending SQL or database commands then receiving results with Java.

# JDBC Drivers Types:


JDBC drivers vary because of the wide variety of operating systems and hardware platforms in
which Java operates.
Sun has divided the implementation types into four categories, Types 1, 2, 3, and 4

Type 1: JDBC-ODBC Bridge Driver:


JDBC bridge is used to access ODBC drivers installed on each client machine. ODBC requires Data
Source Name (DSN) to be configured to your system which represents the target database.

Type 2: JDBC-Native API:


● JDBC API calls are converted into C/C++ API calls which are unique to the database.

● These drivers are provided by the database vendors and used in the same manner as the
JDBC-ODBC Bridge.
● The vendor-specific driver must be installed on each client machine.

● If we change the Database we have to change the native API as it is specific to a database
e.g. Oracle Call Interface (OCI) driver
Type 3: JDBC-Net pure Java:
● Three-tier approach is used to access databases.

● The JDBC clients use standard network sockets(endpoints of a 2-way communication link between
2 programs running on the network) to communicate with middleware application server.

● The socket information is then translated into the call format required by the DBMS, and
forwarded to the database server.
● This kind of driver is extremely flexible, since it requires no code installed on the client and
a single driver can actually provide access to multiple databases.

Type 4: 100% pure Java:


● A pure Java-based driver that communicates directly with vendor's database through socket
connection.
● This is the highest performance driver available for the database and is usually provided by
the vendor itself.
● This kind of driver is extremely flexible; you don't need to install special software on the
client or server.
● These drivers can be downloaded dynamically.

● MySQL's Connector/J driver is a Type 4 driver.

The programming involved to establish a JDBC connection is fairly simple.


Steps:
1. Import JDBC Packages: Add import statements to your Java program to import required
classes in your Java code.
2. Register JDBC Driver: This step causes the JVM to load the desired driver implementation
into memory so it can fulfill your JDBC requests.
3. Database URL Formulation: This is to create a properly formatted address that points to
the database to which you wish to connect.
4. Create Connection Object: Finally, code a call to the DriverManager object's
getConnection( ) method to establish actual database connection.

(Note: Consider db application is Oracle)

1. Import JDBC Packages


● The Import statements includes classes in your code.

● To use the standard JDBC package, which allows you to select, insert, update, and delete data in
SQL tables, add the following imports to your source code:
import java.sql.* ;

2. Register JDBC Driver


● Registering the driver is the process by which the Oracle driver's class file is loaded into memory so
it can be utilized as an implementation of the JDBC interfaces.
● Registration is done only once in the program. You can register a driver in one of two ways.

Class.forName(): dynamically load the driver's class file into memory, which automatically registers it.
This method is preferable because it allows you to make the driver registration configurable and portable.
try
{

Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex)
{
System.out.println("Error: unable to load driver class!");
System.exit(1);
}

DriverManager.registerDriver(): use registerDriver() method if you are using a non-JDK compliant


JVM, such as the one provided by Microsoft.
try
{
Driver myDriver = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver( myDriver );
}
catch(ClassNotFoundException ex)
{
System.out.println("Error: unable to load driver class!");
System.exit(1);
}

3 Database URL Formulation:


After you've loaded the driver, you can establish a connection using the DriverManager.getConnection()
method.
getConnection(String url)
getConnection(String url, Properties prop)
getConnection(String url, String user, String password)

Here each form requires a database URL.


JDBC driver names and database URL.

RDBMS JDBC driver name URL format


MySQL com.mysql.cj.jdbc.Driver jdbc:mysql://hostname:portn/databaseName
ORACLE oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@hostname:portNumber:databaseName
DB2 COM.ibm.db2.jdbc.net.DB2Driver jdbc:db2:hostname:portNumber/databaseName
Sybase com.sybase.jdbc.SybDriver jdbc:sybase:Tds:hostname: port Number/databaseName

4. Create Connection Object:


a) Using a database URL with a username and password:
Assuming you are using Oracle's thin driver, you'll specify a host:port:databaseName value for
the database portion of the URL.
Example: If you have a host at TCP/IP address 192.0.0.1 with a host name of root, and your Oracle
listener is configured to listen on port 1521, and your database name is EMP, then complete
database URL would then be:

jdbc:oracle:thin:@root:1521:EMP

Now you have to call getConnection() method with appropriate username and password to get a
Connection object as follows:

Connection conn = DriverManager.getConnection("jdbc:oracle:thin:@amrood:1521:EMP",


"username", “password”);

b) Using only a database URL:


The database URL includes the username and password and has the following general form:

jdbc:oracle:driver:username/password@databasepath
So the above connection can be created as follows:
String URL = "jdbc:oracle:thin:username/password@amrood:1521:EMP";
Connection conn = DriverManager.getConnection(URL);

c) Using a database URL and a Properties object:


DriverManager.getConnection(String url, Properties info);

A Properties object holds a set of keyword-value pairs. It's used to pass driver properties to the
driver during a call to the getConnection() method.

String URL = "jdbc:oracle:thin:@amrood:1521:EMP";


Properties info = new Properties( );
info.put( "user", "abc" );
info.put( "password", "1" );
Connection conn = DriverManager.getConnection(URL, info);

d) Closing JDBC connections:


Explicitly close all the connections to the database to end each database session.
If you forget, Java's garbage collector will close the connection when it cleans up objects.
(Note: Explicitly close the connection)
To ensure that a connection is closed, you could provide a finally block in your code.
A finally block always executes, regardless if an exception occurs or not.
conn.close();

Executing SQL statement And Query Execution


● Once a connection is obtained we can interact with the database.

● The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and
properties that enable you to send SQL or PL/SQL commands and receive data from your database.
● They also define methods that help bridge data type differences between Java and SQL data types used in a
database.

Interfaces Recommended Use


Used for general-purpose access to your database. Useful when you are using static
Statement
SQL statements at runtime. The Statement interface cannot accept parameters.
Use when you plan to use the SQL statements many times. The PreparedStatement
PreparedStatement
interface accepts input parameters at runtime.
Use when you want to access database stored procedures. The CallableStatement
CallableStatement
interface can also accept runtime input parameters.

The Statement Objects


1. Creating Statement Object:
example:
Statement stmt = null;
try
{
stmt = conn.createStatement( );
...
}
catch (SQLException e) { }
finally
{ ...}
There are 3 methods for execution:

boolean execute(String SQL) : Returns true if a ResultSet object can be retrieved; otherwise, it returns false.

int executeUpdate(String SQL) : Returns no. rows affected by the execution of the SQL statement.

ResultSet executeQuery(String SQL) : Returns a ResultSet object.

2. Closing Statement Object: close()method is used.

Statement stmt = null;


try
{
stmt = conn.createStatement( );
...
}
catch (SQLException e) {. . .}
finally
{
stmt.close();
}

The PreparedStatement Objects


1. Creating PreparedStatement Object:
PreparedStatement pstmt = null;
try
{
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
...
}
catch (SQLException e) { . . .}
finally { . . .}

� All parameters in JDBC are represented by the ? symbol, which is known as the parameter marker.

� You must supply values for every parameter before executing the SQL statement.

� The setXXX() methods bind values to the parameters, where XXX represents the Java data type of the value
you wish to bind to the input parameter.
� If you forget to supply the values, you will receive SQLException.

� The first marker represents position 1, the next position 2, and so forth. This method differs from that of Java
array ,indices, which start at 0.
� execute(), executeQuery() and executeUpdate() also work with the PreparedStatement object.

� However, the methods are modified to use SQL statements that can take input the parameters.

2. Closing PreparedStatement Obeject:


PreparedStatement pstmt = null;
Try
{
String SQL = "Update Employees SET age = ? WHERE id = ?";
pstmt = conn.prepareStatement(SQL);
...
}
catch (SQLException e) {. . .}
finally
{
pstmt.close();
}

The CallableStatement Objects


� It would be used to execute a call to a database stored procedure.
1. Creating CallableStatement Object:
Suppose, you need to execute the following Oracle stored procedure:
CREATE OR REPLACE PROCEDURE getEmpName
(EMP_ID IN NUMBER, EMP_FIRST OUT VARCHAR) AS
BEGIN
SELECT first INTO EMP_FIRST
FROM Employees
WHERE ID = EMP_ID;
END;

NOTE: Above stored procedure has been written for Oracle.


stored procedure - For MySQL as follows to create it in EMP database:

Three types of parameters exist: IN, OUT, and INOUT.


The PreparedStatement object only uses the IN parameter. The CallableStatement object can use all three.
Here are the definitions of each:

Parameter Description
A parameter whose value is unknown when the SQL statement is created. You bind values to IN
IN
parameters with the setABC() methods.
A parameter whose value is supplied by the SQL statement it returns. You retrieve values from
OUT
the OUT parameters with the getABC() methods.
A parameter that provides both input and output values. You bind variables with the setABC()
INOUT
methods and retrieve values with the getABC() methods.

The following code snippet shows how to employ the Connection.prepareCall() method to instantiate a
CallableStatement object based on the preceding stored procedure:

CallableStatement cstmt = null;


try
{
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall(SQL);
...
}
catch (SQLException e) { . . .}
finally { ...}
● The String variable SQL represents the stored procedure, with parameter placeholders.
● Using CallableStatement objects is much like using PreparedStatement objects. You must bind values to all
parameters before executing the statement, or you will receive an SQLException.
● If you have IN parameters, just follow the same rules and techniques that apply to a PreparedStatement
object; use the setABC() method that corresponds to the Java data type you are binding.
● When you use OUT and INOUT parameters you must employ an additional CallableStatement method,
registerOutParameter(). The registerOutParameter() method binds the JDBC data type to the data type
the stored procedure is expected to return.
● Once you call your stored procedure, you retrieve the value from the OUT parameter with the appropriate
geABC() method. This method casts the retrieved value of SQL type to a Java data type.
● Closing CallableStatement Object: close() method will do the job. If you close the Connection object first it
will close the CallableStatement object as well. However, you should always explicitly close the
CallableStatement object to ensure proper cleanup.

CallableStatement cstmt = null;


try
{
String SQL = "{call getEmpName (?, ?)}";
cstmt = conn.prepareCall (SQL);
...
}
catch (SQLException e)
{ ...}
finally
{
cstmt.close();
}

ResultSet
● The SQL statements that read data from a database query return the data in a result set.
● The SELECT statement is the standard way to select rows from a database and view them in a result set.
● The java.sql.ResultSet interface represents the result set of a database query.
● A ResultSet object maintains a cursor that points to the current row in the result set.
● The term "result set" refers to the row and column data contained in a ResultSet object.

The methods of the ResultSet interface can be broken down into three categories:
Navigational methods: used to move the cursor around.
Get methods:used to view the data in the columns of the current row being pointed to by the cursor.
Update methods: used to update the data in the columns of the current row. The updates can then be updated in the
underlying database as well.

JDBC provides following connection methods to create statements with desired ResultSet:

createStatement(int RSType, int RSConcurrency);


prepareStatement(String SQL, int RSType, int RSConcurrency);
prepareCall(String sql, int RSType, int RSConcurrency);

Scrollable and updatable result sets


In JDBC, ResultSets are classified in the following ways.
1. on the basis of ResultSet cursor movement.
2. on the basis of ResultSet concurrency.

on the basis of ResultSet cursor movement there are two types of ResultSets

i)forward only ResultSet:


Allow users to iterate the data only in forward direction.
Public static final int TYPE_FORWARD_ONLY

ii)scrollable ResultSets:
Allow the users to interact with the data in both forward and backward directions.

Scrollable ResultSets can be divided into following two types.


a)ScrollSensitive ResultSet: Allow the later database modifications.

Public static final TYPE_SCROLL_SENSITIVE

b)ScrollInSensitive ResultSet: Allow the later database modifications after creation.


Public static final TYPE_SCROLL_INSENSITIVE

On the basis of ResultSet concurrency there are two types of ResultSets


i)Read only ResultSet:
Allow the users only to read the data.
Public static final int CONCUR_READ_ONLY

ii)updatable ResultSet:
Allow user to update it’s content.
Public static final int CONCUR_UPDATABLE.
If you want to specify particular ResultSet type in JDBC applications then specify the type of ResultSet object at the
time of creation of statement object.
e.g.
public statement createStatement(int forwardonly/ ScrollSensitive/ ScrollInsensitive,int
readonly/updatable)throws SQLException

Scrollable and Updatable Result Sets


● In JDBC applications, by using ScrollSensitive ResultSet object we are able to get the Database later
modifications in ResultSet object automatically.

● In case of SrollSensitive ResultSet object, after performing modifications in Database to reflect those
modifications into the ResultSet object we have to refresh each and every row in ResultSet object.

● To refresh present report


public void refreshRow() throws SQLException

● To move ResultSet cursor after last record


public void afterLast()

● To move ResultSet cursor to first record


public boolean first()

● To move ResultSet cursor to last record


public boolean last()

● To move ResultSet cursor to a particular record


public boolean absolute(int rec_position)
● To skip particular no. of records from the current position
public boolean relative(int no_of_records)

Note:If the int value is positive then cursor will move in forward direction, if it is negative then cursor will
move in backward direction.

● To insert new row in updatable ResultSet object


public void moveToInsertRow()

● To insert record data temporarily in a row


public void updatexxx(int column_index,xxx value)

● In order to make temporary insertion as permanent insertion in the ResultSet object and database
public void insertRow()

Example

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

public class JdbcApp14


{
public static void main(String args[])throws Exception
{
Class.forName(“com.mysql.jdbc.Driver”);
Properties p=new Properties();
Connection con=DriverManager.getConnection(“jdbc:mysql://localhost:3306/test
”,”root”,”system”);

Statement st= con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.


CONCUR_UPDATABLE);

boolean b=st.execute(“select * from emp1″);


System.out.println(b);
ResultSet rs=st.getResultSet();
System.out.println(“————————“);
System.out.println(“ENO ENAME ESAL”);

while(rs.next())
{
System.out.println(rs.getString(“eno”)+” “+ rs.getString(“ename”)+” “+rs.getString(“esal”));
}
System.out.println(“application in pausing state”);
System.out.println(“perform updations at database”);
System.in.read();
rs.beforeFirst();
System.out.println(“data after updations”);
System.out.println(“——————–“);
System.out.println(“ENO ENAME ESAL”);
System.out.println(“——————–“);

while(rs.next())
{
rs.refreshRow();
System.out.println(rs.getString(“eno”)+” “+rs.getString(“ename”)+” “+rs.getString(“esal”));
}
con.close();
}
}

Example
package com.visualbuilder;
import java.sql.*;

public class Up
{
public static void main(String[] args)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:33
06/test","root","root");
Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.
CONCUR_UPDATABLE);

ResultSet rs=stmt.executeQuery("select * from visualbuilder");

while(rs.next())
{
System.out.print("Id is " + rs.getInt("id"));
System.out.println(" Name is "+rs.getString("name"));
}

rs.absolute(1);
rs.updateString(2,"Visual Builder");
rs.updateRow();
rs.beforeFirst();
System.out.println("After Updation");

while(rs.next())
{
System.out.print("Id is " + rs.getInt("id"));
System.out.println(" Name is "+rs.getString("name"));
}

stmt.close();
con.close();
}

catch(Exception e)
{
}
}
}

Output:-
Id is 1 Name is Sun java
Id is 2 Name is Visual Builder
Id is 3 Name is Eclipse
Id is 4 Name is IBM
Id is 5 Name is Jakarta

After Updation
Id is 1 Name is Visual Builder
Id is 2 Name is Visual Builder
Id is 3 Name is Eclipse
Id is 4 Name is IBM
Id is 5 Name is Jakarta

import java.io.*;
import java.sql.*;
import javax.naming.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class JDBCDemo extends HttpServlet


{
public void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException, IOException
{
res.setContentType("text/html");
PrintWriter pr=res.getWriter();

String adm_no=req.getParameter("adm_no");

try
{
Class.forName("com.mysql.cj.jdbc.Driver");
Connection
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test",”root”,”root”)
;
Statement stat=con.createStatement();
ResultSet rs=stat.executeQuery("Select * from SchoolClasses Where
Admission_No="+adm_no);
pr.println("<HTML>");
pr.println("<Head><Title>Using JDBC In Servlet</Title></Head>");
pr.println("<Body>");
pr.println("<Center><H1>Using JDBC In Servlet</h1><HR><BR>");
pr.println("<Table Border=1>");

pr.println("<Tr><Th>Class</Th><Th>RollNo</Th><Th>Name</Th><Th>Father's
Name</Th><Th>DOB</Th><Th>City</Th></Tr>");

while(rs.next())
{
String clas=rs.getString("Class");
String rollno=rs.getString("Roll_No");
String name=rs.getString("Name");
String fname=rs.getString("Father_Name");
String dob=rs.getString("DOB");
String city=rs.getString("City");

pr.println("<Tr><Td>"+clas+"</Td>");
pr.println("<Td>"+rollno+"</Td>");
pr.println("<Td>"+name+"</Td>");
pr.println("<Td>"+fname+"</Td>");
pr.println("<Td>"+dob+"</Td>");
pr.println("<Td>"+city+"</Td></Tr>");
}
pr.println("</Table></Center>");
pr.println("</Body></HTML>");
}
catch(Exception e)
{
pr.println(e);
}
}
}
Row sets
● A Row Set object is a java bean component and extends the ResultSet interface

● Thus, it has a set of JavaBeans properties and follows the JavaBeans event model.

● Allows to establish its own database connection and to execute its own query in order to fill itself with data.

Types of Rowset

1. Connected Rowset:- It is connected to the database connection object like the Resultset. e.g. JDBCRowSet
2. Disconnected RowSet:- It connects to the database whenever required and after finishing the interaction they close
the database connection.

There are following ways to create the JDBCRowSet:-

Passing the ResultSet:- In this approach the data is populated in the object and then you can retrieve the data by
using the get methods as we did in case of the ResultSet.

Exmple:-
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(“select * from employee”);
JdbcRowSet jdbcRs = new JdbcRowSetImpl(rs);

JdbcRowSetImpl is standard implementation of JdbcRowSet

Creating the default object:- This approach is useful if you want to set the data sources dynamically. In this
approach the Database URL, username and password is explicitly set in the RowSetObject.

Exmple:-
JdbcRowSet jdbcRs = new JdbcRowSetImpl();
jdbcRs.setUsername("user");
jdbcRs.setPassword("password");
jdbcRs.setUrl("jdbc:mySubprotocol:mySubname");
jdbcRs.setCommand("select * from EMP ");
jdbcRs.execute();

Basic operation using the JDBCRowSet interface.

import java.sql.*;
import com.sun.rowset.JdbcRowSetImpl;
public class JDBCRowSetExample
{
public static void main(String[] args) throws SQLException
{

JdbcRowSet jdbcRs = new JdbcRowSetImpl();


jdbcRs.setUsername("scott");
jdbcRs.setPassword("tiger");
jdbcRs.setUrl("jdbc:odbc:MyDsn");
jdbcRs.setCommand("select * from employee");
jdbcRs.execute();
while(jdbcRs.next())
{
System.out.println(jdbcRs.getString("ename"));
}
}
}
Ouput:-
Adam
Susan
Adran
Hardy
Tim
Michael

Metadata
Data about the data is called as metadata.
In JDBC there are two types of metadata.
1.Database metadata
2.ResultSet metadata.

JDBC Meta Data is the collective information about the data structure and property of a column available in table.
The meta data of any table tells you the name of the columns, datatype of column and constraint used to enter the
value of data into column of the table.

Example
import java.sql.*;
public class Jb
{
public static void main(String args[])
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(“jdbc:mysql://localhost:3306/test”,root,root);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from person");
ResultSetMetaData metaData = rs.getMetaData();

int rowCount = metaData.getColumnCount();


System.out.println("Table Name : " + metaData.getTableName(2));

System.out.println("Field \t size\t DataType");


for(int i = 0; i < rowCount; i++)
{
System.out.print(metaData.getColumnName(i + 1) + "\t");
System.out.print(metaData.getColumnDisplaySize(i+1) +"\t");
System.out.println(metaData.getColumnTypeName(i 1));
}
}
catch (Exception e)
{
System.out.println(e);
}
}
}

Output:-
Table Name: person
Field Size DataTypes
id 2 VARCHAR
cname 50 VARCHAR
dob 10 DATE

Transaction

● Transaction represents a single unit of work.

● The ACID properties describes the transaction management well.

● ACID stands for Atomicity, Consistency, isolation and durability.

● Atomicity means either all successful or none.

● Consistency ensures bringing the database from one consistent state to another consistent state.

● Isolation ensures that transaction is isolated from other transaction.

● Durability means once a transaction has been committed, it will remain so, even in the event of errors, power
loss etc.

Advantage of Transaction Mangaement


– fast performance It makes the performance fast because database is hit at the time of commit.

In JDBC, Connection interface provides methods to manage transaction.

Method Description
void setAutoCommit(boolean status) It is true bydefault means each transaction is committed by default.
void commit() commits the transaction.
void rollback() cancels the transaction.

You might also like