0% found this document useful (0 votes)
21 views62 pages

AJP2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views62 pages

AJP2

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

What is Database?

A database is an organized collection of data, so that it can be easily


accessed and managed.

You can organize data into tables, rows, columns, and index it to make it
easier to find relevant information.

Database handlers create a database in such a way that only one set of
software program provides access of data to all the users.

The main purpose of the database is to operate a large amount of


information by storing, retrieving, and managing data.

There are many dynamic websites on the World Wide Web nowadays which
are handled through databases. For example, a model that checks the
availability of rooms in a hotel. It is an example of a dynamic website that
uses a database.

There are many databases available like MySQL, Sybase, Oracle,


MongoDB, Informix, PostgreSQL, SQL Server, etc.
Database Languages in DBMS
A DBMS has appropriate languages and interfaces to express database
queries and updates.
Database languages can be used to read, store and update the data in the
database.
Types of Database Languages
Data Definition Language (DDL)
DDL stands for Data Definition Language. It is used to define database structure
or pattern.
It is used to create schema, tables, indexes, constraints, etc. in the database.

Data Manipulation Language (DML)


DML stands for Data Manipulation Language. It is used for accessing and
manipulating data in a database. It handles user requests.

Data Control Language (DCL)


DCL stands for Data Control Language. It is used to retrieve the stored or saved
data.
The DCL execution is transactional. It also has rollback parameters.

Transaction Control Language (TCL)


TCL is used to run the changes made by the DML statement. TCL can be
grouped into a logical transaction.
MODULE -2

JDBC Programming
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and
execute the query with the database. It is a part of JavaSE (Java Standard
Edition). JDBC API uses JDBC drivers to connect with the database

There are four types of JDBC drivers:

JDBC-ODBC Bridge Driver,


Native Driver,
Network Protocol Driver, and
Thin Driver
What is API
API (Application programming interface) is a document that contains a description of
all the features of a product or software. It represents classes and interfaces that
software programs can follow to communicate with each other. An API can be
created for applications, libraries, operating systems, etc.

Why Should We Use JDBC

Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC
drivers (written in Java language).

We can use JDBC API to handle database using Java program and can perform the following
activities:
1.Connect to the database
2.Execute queries and update statements to the database
3.Retrieve the result received from the database.
Java Database Connectivity with 5 Steps

There are 5 steps to connect any java application with the database using
JDBC. These steps are as follows:

1.Register the Driver class

2.Create connection

3.Create statement

4.Execute queries

5.Close connection
1) Register the driver class
The forName() method of Class class is used to register the driver
class. This method is used to dynamically load the driver class.

Syntax of forName() method

public static void forName(String className)throws ClassNotFoundException

2) Create the connection object


The getConnection() method of DriverManager class is used to establish connection
with the database.
Syntax of getConnection() method

1) public static Connection getConnection(String url)throws SQLException


2) public static Connection getConnection(String url,String name,String passwor
d)
throws SQLException
3) Create the Statement object

The createStatement() method of Connection interface is used to create


statement. The object of statement is responsible to execute queries with the
database.
public Statement createStatement()throws SQLException

4) Execute the query


Syntax of executeQuery() method

The executeQuery() method of Statement interface is used to execute queries


to the database. This method returns the object of ResultSet that can be used
to get all the records of a table.

5) Close the connection object


Syntax of close() method

By closing connection object statement and ResultSet will be


closed automatically. The close() method of Connection interface
is used to close the connection.
Creating a SQL Query
Required Steps

The following steps are required to create a new Database using JDBC
application −

Import the packages − Requires that you include the packages containing the
JDBC classes needed for database programming. Most often, using import
java.sql.* will suffice.

Open a connection −
Requires using the DriverManager.getConnection() method to create a
Connection object, which represents a physical connection with a database
server.

Execute a query − Requires using an object of type Statement for building and
submitting an SQL statement to create a table in a seleted database.

Clean up the environment − try with resources automatically closes the


resources.
Getting the Results
import java.sql.Connection;
Import java.sql.DriverManager;
import java.sql.ResultSet;
Import java.sql.SQLException;
Import java.sql.Statement;
public class JDBCExample
{
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Registration";
)
{
while(rs.next()
)
{
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last")); }

}
}
catch (SQLException e)
{
e.printStackTrace();
}}}
Now let us compile the above example as follows −
C:\>javac JDBCExample.java C:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample

ID: 100, Age: 18, First: SAI, Last: RAM


ID: 101, Age: 25, First: Mahi, Last: ram
ID: 102, Age: 30, First: Zam, Last: Zam
ID: 103, Age: 28, First: Sumit, Last: Mittal
Updating Database Data

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
static final String DB_URL = "jdbc:mysql://localhost/TUTORIALSPOINT";
static final String USER = "guest";
static final String PASS = "guest123";
static final String QUERY = "SELECT id, first, last, age FROM Registration";
public static void main(String[] args) {
// Open a connection
try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);
Statement stmt = conn.createStatement();
)
{
String sql = "UPDATE Registration " +
"SET age = 30 WHERE id in (100, 101)";
stmt.executeUpdate(sql);
ResultSet rs = stmt.executeQuery(QUERY);
while(rs.next()){
//Display values
System.out.print("ID: " + rs.getInt("id"));
System.out.print(", Age: " + rs.getInt("age"));
System.out.print(", First: " + rs.getString("first"));
System.out.println(", Last: " + rs.getString("last"));
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
Now let us compile the above example as follows −
C:\>javac JDBCExample.javaC:\>
When you run JDBCExample, it produces the following result −
C:\>java JDBCExample
ID: 100, Age: 30, First: Zara, Last: Ali
ID: 101, Age: 30, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
SQL Exception
Exception handling allows you to handle exceptional conditions such as program-
defined errors in a controlled fashion.
When an exception condition occurs, an exception is thrown. The term thrown
means that current program execution stops, and the control is redirected to the
nearest applicable catch clause. If no applicable catch clause exists, then the
program's execution ends.

JDBC Exception handling is very similar to the Java Exception handling but for
JDBC, the most common exception you'll deal with is java.sql.SQLException.

SQLException Methods

An SQLException can occur both in the driver and the database. When such an
exception occurs, an object of type SQLException will be passed to the catch
clause.

The passed SQLException object has the following methods available for
retrieving additional information about the exception −
Method Description

getErrorCode( ) Gets the error number associated with the exception.

getMessage( ) Gets the JDBC driver's error message for an error, handled by the driver or gets the
Oracle error number and message for a database error.

getSQLState( ) Gets the XOPEN SQLstate string. For a JDBC driver error, no useful information is
returned from this method. For a database error, the five-digit XOPEN SQLstate code
is returned. This method can return null.

getNextException( ) Gets the next Exception object in the exception chain.


What is SQL Warning In JDBC?

SQLWarning is a subclass of SQLException that holds database access


warnings. Warnings do not stop the execution of a specific application, as
exceptions do.
A warning may be retrieved on the Connection object, the Statement object,
PreparedStatement and CallableStatement objects, or on the ResultSet
using getWarnings method.

public class SQLWarning


extends SQLException
The SQLWarning class provides information on a database access warnings. Warnings are
silently chained to the object whose method caused it to be reported.

Class java.sql.SQLWarning
java.lang.Object | +----java.lang.Throwable | +----java.lang.Exception | +----
java.sql.SQLException | +----java.sql.SQLWarning
SQLWarning()
Construct an SQLWarning ; reason defaults to null, SQLState defaults to null and vendorCode
defaults to 0.
SQLWarning(String)
Construct an SQLWarning with a reason; SQLState defaults to null and vendorCode defaults to 0.
SQLWarning(String, String)
Construct an SQLWarning with a reason and SQLState; vendorCode defaults to 0.
SQLWarning(String, String, int)
Construct a fully specified SQLWarning.
SQLWarning warning = stmt.getWarnings();
while (warning != null)
{
System.out.println("Message: " + warning.getMessage());
System.out.println("SQLState: " + warning.getSQLState());
System.out.println("Vendor error code: " +
warning.getErrorCode());
warning = warning.getNextWarning();
}
JDBC
STATE MENTS
1.STATEMENT

2.PREPARED STATEMENT

3.CALLABLE STATEMENT

1.STATEMENT

We can use normal Statement to execute multiple queries

Ex. St.execute query(insert)


St.execute query(update)
St.execute query(delete)
2.PREPARED STATEMENT

If we want to work with only one query ,but should be executed multiple times
then we should go for Prepared Statement.

3.CALLABLE STATEMENT

If we want to work with stored procedures and functions then we should go for
Callable statement.

stored procedures: is a Prepared SQL code that you can save , so the code
can be reused over and over again. So if you have an sql query that you write
over and over again save it as a stored procedure and then just call it to
execute
Statement interface

The Statement interface provides methods to execute queries with the database. The
statement interface is a factory of ResultSet i.e. it provides factory method to get the
object of ResultSet.
Commonly used methods of Statement interface:
The important methods of Statement interface are as follows:

1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It


returns the object of ResultSet.

2) public int executeUpdate(String sql): is used to execute specified query, it may be


create, drop, insert, update, delete etc.

3) public boolean execute(String sql): is used to execute queries that may return
multiple results.

4) public int[] executeBatch(): is used to execute batch of commands.


PreparedStatement interface

The PreparedStatement interface is a subinterface of Statement. It is used to


execute parameterized query.

Let's see the example of parameterized query:

String sql="insert into emp values(?,?,?)";

As you can see, we are passing parameter (?) for the values. Its value will be
set by calling the setter methods of PreparedStatement.

Why use PreparedStatement?

Improves performance: The performance of the application will be faster if


you use PreparedStatement interface because query is compiled only once.
2. Prepare Statement
Instead of hardcoding queries like,

select * from students where age>10 and name ='Chhavi‘

Set parameter placeholders(use question mark for placeholders) like,

select * from students where age> ? and name = ?


Java CallableStatement Interface

CallableStatement interface is used to call the stored procedures and


functions.

We can have business logic on the database by the use of stored procedures
and functions that will make the performance better because these are
precompiled.

Suppose you need the get the age of the employee based on the date of birth,
you may create a function that receives date as the input and returns age of
the employee as the output.
JDBC Types
1.JDBC-ODBC bridge driver
2.Native-API driver
3.Network Protocol driver
4.Thin driver

JDBC Driver is a software component that enables java application to interact


with the database. There are 4 types of JDBC drivers:

The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function
calls. This is now discouraged because of thin driver.
JDBC-ODBC bridge driver

The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now
discouraged because of thin driver.
Native-API driver

The Native API driver uses the client-side libraries of the database. The driver converts JDBC
method calls into native calls of the database API. It is not written entirely in java.

Network Protocol driver


The Network Protocol driver uses middleware (application server) that converts
JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully
written in java.
The thin driver converts JDBC calls directly into the vendor-specific database protocol.
That is why it is known as thin driver. It is fully written in Java language.
Transaction Management in
JDBC
Transaction represents a single unit of work.

The ACID properties describes the transaction management well. ACID


stands for Atomicity, Consistency, isolation and durability.

1.Atomicity means either all successful or none.

2.Consistency ensures bringing the database from one consistent state to


another consistent state.

3.Isolation ensures that transaction is isolated from other transaction.

4.Durability means once a transaction has been committed, it will


remain so, even in the event of errors, power loss etc.
Result Set interface

The result set is an object that represents a set of data returned


from a data source, usually as the result of a query. The result set
contains rows and columns to hold the requested data elements, and it
is navigated with a cursor.

The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor
points to before the first row.
JDBC Updatable ResultSet:

In this tutorial, I am going to tell you how to make a ResultSet as Updatable. You
can find How to make a ResultSet as Updatable ResultSet and Scrollable here.
To make the ResultSet object updatable and scrollable we must use the following
constants which are present in the ResultSet interface.

TYPE_SCROLL_SENSITIVE
CONCUR_UPDATABLE

The above two constants must be specified while we are creating Statement
object by using the following method:
On the above ResultSet object, we can perform the following three operations:
inserting a record,
deleting a record and
updating a record.

Steps to insert a record through ResultSet object:


We can insert the record in the database through ResultSet object
using absolute() method, but before inserting a record, you need to decide at
which position you are inserting, since the absolute() method takes a position as a
parameter where it to be inserted.
Step-1 :
rs.absolute (3);

Step-2 :
Since we are inserting a record we must use the following method to make the
ResultSet object hold the record.
rs.moveToInsertRow ();
Java ResultSetMetaData Interface

The metadata means data about data i.e. we can get further information from the data.
If you have to get metadata of a table like total number of column, column name,
column type etc. , ResultSetMetaData interface is useful because it provides methods to
get metadata from the ResultSet object.

Commonly used methods of ResultSetMetaData interface

Method Description

public int getColumnCount()throws it returns the total number of columns in


SQLException the ResultSet object.

public String getColumnName(int it returns the column name of the specified


index)throws SQLException column index.
Executing SQL Queries

Java Database Connectivity (JDBC) is an Application Programming Interface (API) used to


connect Java application with Database. JDBC is used to interact with various type of Database
such as Oracle, MS Access, My SQL and SQL Server. It allows java program to execute SQL
statement and retrieve result from database.

The following steps are involved in executing SQL statements in JDBC:


1. Load the JDBC driver.
2. Specify the name and location (given as a URL) of the database being used.
3. Connect to the database with a Connection object.
4. Execute a SQL query using a Statement object.
5. Get the results in a ResultSet object.
6. Finish by closing the ResultSet, Statement and Connection objects.
Example 2: This example describes how to create a new table using the
CREATE DDL command.

CREATE TABLE Student


(
Roll_No. Int ,
First_Name Varchar (20) ,
Last_Name Varchar (20) ,
Age Int ,
Marks Int ,
);
Stu_Id Name Marks age

100 Abhay 80 Noida U.P


101 Sushil 75 Jaipur Rajasthan
102 Ankit 90 Gurgaon Haryana
103 Yogesh 93
Let's take the Student table:

SELECT DML Command


SELECT is the most important data manipulation command in Structured
Query Language. The SELECT command shows the records of the
specified table. It also shows the particular record of a particular column
by using the WHERE clause.

Example 2: This example shows all the values of a specific column


from the table.
SELECT St_Id, St_Marks FROM Student ;

Stu_Id Marks

100 80
101 75

102 90

103 93
UPDATE DML Command
UPDATE is another most important data manipulation command in Structured
Query Language, which allows users to update or modify the existing data in
database tables.
Syntax of UPDATE Command
UPDATE Table_name SET [column_name1= value_1, ….., column_nameN = val
ue_N] WHERE CONDITIO

UPDATE Student SET Marks= 80 WHERE St_Id = '102' ;

Stu_Id Marks

100 80
101 75

102 80

103 93

You might also like