AJP2
AJP2
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.
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.
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
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:
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.
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.
}
}
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
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
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.
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
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:
3) public boolean execute(String sql): is used to execute queries that may return
multiple results.
As you can see, we are passing parameter (?) for the values. Its value will be
set by calling the setter methods of PreparedStatement.
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
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.
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.
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.
Method Description
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
Stu_Id Marks
100 80
101 75
102 80
103 93