Lecture Notes on Advanced Java Module-01
Lecture Notes on Advanced Java Module-01
Programming
Dr. SIBO PRASAD PATRO
Assistant Professor
Department of Computer Science and Engineering
School of Engineering and Technology
GIET University, Gunupur, Odisha – 765022
MOB: 9437234031 EMAIL: sibofromgiet@giet.edu
Class-01
Topics to be Covered
• Basics of JDBC:
• Introduction to JDBC
• Need of JDBC
• JDBC Drivers (4 types)
• Architecture of JDBC
• Components of JDBC (Classes and Interfaces).
• Programming with JDBC:
• Creating a DATABASE (ORACLE)
• First Program to connect to the DATABASE created
• Loading the Driver, Establishing the Connection
• Creating Statements (Statement/ PreparedStatement/
CallableStatement), Executing a SQL Query, Different types of SQL
Queries.
05/26/2025 Prof. Sibo Prasad Patro 2
Introduction
• Advanced Java includes extra tools and technologies beyond the basics of
Core Java.
• Advanced Java is the collection of technologies and tools that enable
developers to create dynamic and secure applications, including features
such as JDBC (Java Database Connectivity), Servlets , and JSP (JavaServer
Page) are being used for generating and making interactive dynamic content,
the most important feature of advanced Java is JPA (Java Persistence API),
that is used for managing relational databases, Spring Framework that
encompasses the modules for dependency injection, Spring MVC
Framework, and AOP (Aspect-Oriented Programming), and Spring Security
that ensures the authentication, and authorization of the application.
• Moreover, It is important for creating dynamic websites, big software for
businesses, and connecting Java programs with databases.
Prerequisites For Learning Advanced Java
This interface represents a static SQL statement. Using the Statement object
and its methods, you can execute an SQL statement and get the results of it.
Statement
It provides methods such as execute(), executeBatch(), executeUpdate() etc. To
execute the statements.
Components of JDBC (Classes and
Interfaces).
This represents a precompiled SQL statement. An SQL statement is compiled and
stored in a prepared statement and you can later execute this multiple times. You can
get an object of this interface using the method of the Connection interface named
PreparedStatement prepareStatement(). This provides methods such as executeQuery(),
executeUpdate(), and execute() to execute the prepared statements and getXXX(),
setXXX() methods to set and get the values of the bind variables of the prepared
statement.
Using an object of this interface you can execute the stored procedures. This returns
single or multiple results. It will accept input parameters too. You can create a
CallableStatement CallableStatement using the prepareCall() method of the Connection interface.
Just like Prepared statement, this will also provide setXXX() and getXXX() methods
to pass the input parameters and to get the output parameters of the procedures.
This interface represents the connection with a specific database. SQL statements are
executed in the context of a connection. This interface provides methods such as
Connection
close(), commit(), rollback(), createStatement(), prepareCall(), prepareStatement(),
setAutoCommit() setSavepoint() etc.
Components of JDBC (Classes and
Interfaces).
This interface represents the database result set, a table which is generated by
ResultSet executing statements. This interface provides getter and update methods to retrieve
and update its contents respectively.
This interface is used to get the information about the result set such as, number of
columns, name of the column, data type of the column, schema of the result set,
ResultSetMetaData
table name, etc It provides methods such as getColumnCount(), getColumnName(),
getColumnType(), getTableName(), getSchemaName() etc.
Example of creating JDBC
Application overview
https://dev.mysql.com/downloads/file/?
id=531940
https://dev.mysql.com/downloads/file/?id=530070
JDBC Drivers (4 Types)
• JDBC drivers are client-side adapters (installed on the client machine, not
on the server) that convert requests from Java programs to a protocol that
the DBMS can understand. JDBC drivers are the software components
which implements interfaces in JDBC APIs to enable java application to
interact with the database.
• There are four types of JDBC Drivers listed below,
• Type I: Bridge
• Type II: Native
• Type III: Middleware
• Type IV: Pure
JDBC Drivers (4 Types)
1. Type 1: JDBC-ODBC Bridge Driver
• Description: This driver translates JDBC calls into ODBC (Open Database Connectivity)
calls and then communicates with the database using the ODBC driver.
• Advantages: Easy to use and can connect to any database that supports ODBC.
• Disadvantages: Slower performance due to the added layer of ODBC. Requires ODBC
driver installation on the client machine.
(deprecated, adds overhead).
2. Type 2: Native-API Driver (Partly Java Driver)
• Description: This driver converts JDBC calls into database-specific native calls using the
database's native client API (e.g., Oracle OCI, MySQL C API).
• Advantages: Faster than Type 1 because it uses native code.
• Disadvantages: Requires native database client libraries on the client machine. Not
portable as it is specific to a particular database.
(faster but requires native libraries).
JDBC Drivers (4 Types)
3. Type 3: Network Protocol Driver (Middleware Driver)
• Description: This driver sends JDBC calls to a middleware server, which then translates
them to database-specific calls. The middleware can handle connections to multiple
databases.
• Advantages: No need for database-specific client libraries on the client machine. Suitable
for internet-based applications.
• Disadvantages: Requires an additional middleware server, which can add complexity and
overhead.
(requires middleware, flexible).
4. Type 4: Thin Driver (Pure Java Driver)
• Description: This driver directly converts JDBC calls to database-specific protocol calls. It
is entirely written in Java and communicates directly with the database.
• Advantages: Platform-independent, no need for additional client software or middleware.
High performance.
• Disadvantages: Specific to a particular database, so a different driver is needed for each
database type.
pure Java, platform-independent, preferred choice).
1. JDBC-ODBC 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. These drivers uses bridging technology. They require
installation/configuration on client machines. These drivers are not recommended for Web. Example of Type I Driver
is ODBC Bridge.
Advantages:
•easy to use.
•can be easily connected to any database.
Disadvantages:
•Performance degraded because JDBC method call is converted
into the ODBC function calls.
•The ODBC driver needs to be installed on the client machine.
Advantage:
•performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
•The Native driver needs to be installed on the each client
machine.
•The Vendor client library needs to be installed on client
machine.
3. 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.They are very flexible and allow access to multiple databases using
one driver. There is only the need to download one driver, but it is another server
application to install and maintain. An example of it is Symantec DBAnywhere.
Advantage:
•No client side library is required because of application
server that can perform many tasks like auditing, load
balancing, logging etc.
•Platform independent and Database independent driver.
Disadvantages:
•Network support is required on client machine.
•Requires database-specific coding to be done in the
middle tier.
•Maintenance of Network Protocol driver becomes
costly because it requires database-specific coding to be
done in the middle tier.
4. THIN Driver
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. These drivers use Java networking libraries to talk directly to database
engines. A disadvantage here is the need to download a new driver for each
database engine. Examples include Oracle, mySQL etc.
Advantage:
•Better performance than all other drivers.
•Platform independent (driver purely written in
java)
Disadvantage:
•Drivers depend on the Database.
Which Driver should be used
• If you are accessing one type of database, such as Oracle, Sybase, or IBM, the
preferred driver type is 4.
• Type 2 drivers are useful in situations, where a type 3 or type 4 driver is not
available yet for your database.
Class.forName("oracle.jdbc.driver.OracleDriver");
Class.forName("com.mysql.cj.jdbc.Driver");
2. Create the connection object
The getConnection() method of DriverManager class is used to establish connection with the database.
1) public static void registerDriver(Driver is used to register the given driver with
driver): DriverManager.
1) public Statement createStatement(): creates a statement object that can be used to execute SQL
queries.
2) public Statement createStatement(int resultSetType,int resultSetConcurrency): Creates a Statement
object that will generate ResultSet objects with the given type and concurrency.
3) public void setAutoCommit(boolean status): is used to set the commit status.By default it is true.
4) public void commit(): saves the changes made since the previous commit/rollback permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.
Statement stmt = con.createStatement(ResultSet.TYPE 2) public boolean previous(): is used to move the cursor to the one row
previous from the current position.
_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPD 3) public boolean first(): is used to move the cursor to the first row in
ATABLE); result set object.
4) public boolean last(): is used to move the cursor to the last row in
result set object.
5) public boolean absolute(int row): is used to move the cursor to the specified
row number in the ResultSet object.
6) public boolean relative(int row): is used to move the cursor to the relative row
number in the ResultSet object, it may be
positive or negative.
7) public int getInt(int columnIndex): is used to return the data of specified column
index of the current row as int.
8) public int getInt(String columnName): is used to return the data of specified column
name of the current row as int.
9) public String getString(int is used to return the data of specified column
columnIndex): index of the current row as String.
10) public String getString(String is used to return the data of specified column
columnName): name of the current row as String
JDBC
Executing Query & Processing
Results
4
Objectives
At the end of this module, you will be able to:
47
Stage 2:
Query
Connect
Clos
e
48
Stage 2:
Query
• Once a connection is established, it is used to pass SQL statements to its
underlying
database.
• A Statement object is used to send SQL statements to a database. The Statement
interface
provides basic methods for executing statements and retrieving results.
• The JDBC API does not put any restrictions on the kinds of SQL statements that can be
sent; this provides a great deal of flexibility, allowing the use of database-specific
statements or even non-SQL statements. It requires, however, that the user be responsible
for making sure that the underlying database can process the SQL statements being sent
and suffer the consequences if it cannot. For example, an application that tries to send a
stored procedure call to a DBMS that does not support stored procedures will be
unsuccessful and will generate an exception.
49
Query: The
Statement Object
To execute SQL statements use Statement Object.
You need an active connection to create a JDBC statement
Statement object has three methods to execute a SQL statements:
executeQuery() for SELECT statements
executeUpdate() for INSERT, UPDATE, DELETE, or DDL
statements
execute() for either type of statement
50
Query: The Statement
Object
The slide lists the three methods you can call to execute a SQL statement. The following
slides describe how to call each method. execute() is useful for dynamically executing
an unknown SQLstring.
JDBC provides two other statement objects:
PreparedStatement, for precompiled SQLstatements, is covered later.
CallableStatement, for statements that execute stored procedures, is also covered later.
Objects and Interfaces:
java.sql.Statement is an interface, not an object. When you declare a Statement object
and initialize it using the createStatement() method, you are creating the implementation of
the Statement interface supplied by the Oracle driver or any other driver that you are
using.
51
How to Query the
Database?
1. To execute SQL statement , we should first create Statement object,
as:
Statement stmt = conn.createStatement();
52
How to Query the
Database?
Once a connection to a particular database is established, that connection can be used to
send SQL statements. A Statement object is created with the Connection method
createStatement, as in the following code fragment:
Statement stmt = conn.createStatement();
The SQL statement that will be sent to the database is supplied as the argument to one
of
the execute methods on a Statement object.
This is demonstrated in the following example, which uses the method executeQuery:
ResultSet rset = stmt.executeQuery("SELECT a, b, c FROM Table2");
The variable rset references a result set discussed in the following sections.
53
Querying the Database:
Examples
Following Statements are used to execute Select
statement:
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery
("select NAME, VERTICAL from STUDENT");
54
Querying the
Database
As mentioned earlier, the Statement interface provides three different methods for
executing SQL statements: executeQuery, executeUpdate, and execute. The correct method
to use is determined by what the SQL statement produces.
The method executeQuery() method is used for statements that produce a result set, such
as
SELECT statements.
The method executeUpdate() method is used to execute DML statements and also SQL
DDL (Data Definition Language) statements. The return value of executeUpdate() method
is an integer (referred to as the update count) that indicates the number of rows that were
affected. For statements such as CREATE TABLE or DROP TABLE, which do not operate
on rows, the executeUpdate() method is returns always zero.
The method execute() is used to execute statements that return more than one result
set,
more than one update count, or a combination of the two.
Process the
Results
Now that we have obtained the results of querying the database in the ResultSet object,
we need to iterate through this object and retrieve its contents for further processing in the
Java program.
Connect
Query
Step through the results
Close
Process the Results: The ResultSet
Object
ResultSet is an object that contains the results of executing a SQL
statement
To retrieve the data from the columns, we can use getXXX() method
Process the Results: The ResultSet
Object
The results are available in ResultSet object. In other words, it contains the rows that
satisfy
the conditions of the query.
The data stored in a ResultSet object is retrieved through a set of get methods that
allows access to the various columns of the current row.
The ResultSet.next() method moves the cursor to the next row in the ResultSet object.
The general form of a result set is a table with column headings and the
corresponding values returned by a query.
Process the Results: The ResultSet
Object
For example, if your query is SELECT column_a, column_b, column_c FROM Table1,
your
result set will have the following form:
column_a column_b column_c
------ ------ -------
12345 Cupertino 2459723.495
83472 Redmond 1.0
83492 Boston 35069473.43
We can retrieve the results using the methods of ResultSet interface. Each of these
getXXX() methods attempts to convert the column value to the specified Java type and
returns a suitable Java value. For example, getInt() method gets the column value as an int
value, getString() method gets the column value as a String value, and geLong() method
returns the column value as a long value.
How to Process the
Result?
while (rset.next()) { … }
while (rset.next()) {
String name = rset.getString(“NAME");
String supervisor =
rset.getString(“SUPERVISOR");
… // Process or display the data
}
How to Process the
Result?
A ResultSet object maintains a cursor, which points to its current row of data. The cursor
moves down one row each time the method next is called. When a ResultSet object is first
created, the cursor is positioned before the first row, so the first call to the next method
puts the cursor on the first row, making it the current row. ResultSet rows can be retrieved
in sequence from top to bottom as the cursor moves down one row with each successive
call to the method next.
When a cursor is positioned on a row in a ResultSet object (not before the first row or
after the last row), that row becomes the current row. This means that any methods called
while the cursor is positioned on that row will operate on values in that row (methods
such as getXXX).
A cursor remains valid until the ResultSet object or its parent Statement object is closed.
Setting up
classpath
Before we can execute any JDBC program, we have to set the classpath for the type IV
driver. We need to know, what is the name of the jar file, which contains type IV driver.
The jar file, which we will be using is classes12.jar. This jar file is found within jlib
folder under oracle folder hierarchy.
For e.g., In my system, classes12.jar is within the following path :
E:\app\harb\product\11.1.0\db_1\oui\jlib\classes.jar
Add the above path(including classes12.jar) to the classpath that you have already set.
If you don’t have classpath set in your system, create a new enviroment variable and
add the following as its value :
Variable name : classpath
Variable value : .; E:\app\harb\product\11.1.0\db_1\oui\jlib\classes12.jar;
Setting up classpath
(Contd.).
Setting up classpath
(Contd.).
If you are using eclipse IDE, then it will not recognize the environment variable,
classpath. You will have to add classes12.jar, as an external jar file to the build path.
Exampl
e java.sql.*;
import
class MakeConnection1{
Connection con;
Statement stmt;
ResultSet rs;
MakeConnection1(){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection
("Jdbc:Oracle:thin:@localhost:1521:ORCL","scott","tige
r");
stmt=con.createStatement();
rs=stmt.executeQuery("Select ename, sal from emp");
while(rs.next())
System.out.println(rs.getString(1)+"
"+rs.getInt(2));
Example (Contd.).
conn.close();
} // end of try
block
catch(SQLException e){
System.out.println
(e);
}
catch(ClassNotFoundException e){
System.out.println(e);
}
}
}
public class TestConnection1{
public static void main(String args[]){
new MakeConnection1();
}
Example (Contd.).
Quiz
1. What does the next() method invoked on the result set object return
a) String
b) int
c) boolean
d) float
2. Which one of the following method can be invoked on the connection object to create an empty Statement
object
a) createStatement();
b) getStatement();
c) prepareStatement(); Answers
d) executeStatement(); :
1:
c
2:
Close
Connection
Connect
Query
Close the result set
Process
results Close the statement
The method close() is provided so that a ResultSet object can be closed explicitly,
thereby immediately releasing the resources held by the ResultSet object.
This could be necessary when several statements are being used and the automatic close
does not occur soon enough to prevent database resource conflicts.
How to Close the
Connection?
1. Close the ResultSet
object
rset.close();
3. Close the
connection
conn.close();
How to Close the
Connection?
When a connection is in auto-commit mode, the statements being executed within it are
committed or rolled back when they are completed. A statement is considered complete
when it has been executed and all its results have been returned.
For the method executeQuery, which returns one result set, the statement is
completed
when all the rows of the ResultSet object have been retrieved.
For the method executeUpdate, a statement is completed when it is executed. In the rare
cases where the method execute is called, however, a statement is not complete until all of
the result sets or update counts it generated have been retrieved.
How to Close the
Connection?
Statement objects will be closed automatically by the Java garbage collector.
Nevertheless, it is recommended as good programming practice that they be closed
explicitly when they are no longer needed. This frees DBMS resources immediately and
helps avoid potential memory problems.
The same connection object can be used to execute multiple statements and retrieve many
result sets. However, once all the work with the database is over, it is a good programming
practice to close the connection explicitly. If this is not closed, after a particular timeout
period defined at the database, the connection is automatically closed. Nevertheless, this
would mean that till the timeout, this connection is not available to any other users of the
database. Hence, explicit closing of the connection is recommended.
Qui
z
1. Which of the following methods is not used for querying
database?
a. executeQuery()
b. executeStatement()
c. executeUpdate()
d. execute()
2. Which of the method is used to close a connection?
a. connection.close();
b. connection.terminate();
c. connection.exit();
d. None of the above Answer
s:
1. B
2. A
Thank
You
JDBC
MetaData & PreparedStatement
7
Objective
sAt the end of this module, you will be able to:
– Analyze how to use the Metadata objects to retrieve more information about
the database or the result set
77
The DatabaseMetaData
Object
• Metadata is data about data
• DatabaseMetaData is an interface to get comprehensive information about the database
as a whole
• This object provides more than 100 methods to obtain information about the database
78
The DatabaseMetaData
Object
The following are some examples of DatabaseMetaData methods:
getColumnPrivileges(): Get a description of the access rights for a table's columns.
getColumns(): Get a description of table columns.
getDatabaseProductName(): Get the name of this database product.
getDriverName() : Get the name of this JDBC driver.
storesLowerCaseIdentifiers(): Does the database store mixed-case SQL identifiers in
lower case?
supportsAlterTableWithAddColumn(): Is ALTER TABLE with add column supported?
supportsFullOuterJoins(): Are full nested outer joins supported?
79
How to obtain Database
Metadata?
1. To get the DatabaseMetaData
Object
DatabaseMetaData dbmd = conn.getMetaData();
80
The DatabaseMetaData
Object
This interface is implemented by driver vendors to let users know the capabilities of a Database Management System (DBMS) in combination
with thedriver based on JDBC technology ("JDBC driver") that is used with it. Different relational
DBMSs often support different features, implement features in different ways, and use different data
types. In addition, a driver may implement a feature on top of what the DBMS offers. Information
returned by methods in this interface applies to the capabilities of a particular driver and a particular
DBMS working together.
A user for this interface is commonly a tool that needs to discover how to deal with the underlying
DBMS. This is especially true for applications that are intended to be used with more than one DBMS.
For example:
getURL(): Returns the URL for the DBMS
getSQLKeywords(): Retrieves a comma-separated list of all of this database's SQL keywords that are
NOT also SQL92 keywords.
supportsTransactions(): Retrieves whether this database supports transactions. If not, invoking the
method commit is no use, and the isolation level is TRANSACTION_NONE.
supportsSelectForUpdate(): Retrieves whether this database supports SELECT FOR
UPDATE
statements. 81
Example on
DatabaseMetaData object
import java.sql.*;
import java.io.*;
class MakeConnection3
{ Connection conn;
Statement stmt;
String s1, s2;
DatabaseMetaData dbmd;
MakeConnection3()
{ try {
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection("Jdbc:Oracle:thin:@localhost:1521:
orcl","scott","tiger");
contd..
82
Example on DatabaseMetadata
(Contd.).
dbmd = conn.getMetaData();
s1 = dbmd.getURL();
s2 =
dbmd.getSQLKeywords();
boolean b1 = dbmd.supportsTransactions();
boolean b2 = dbmd.supportsSelectForUpdate();
System.out.println("URL : "+s1);
System.out.println("SQL Keywords :"+s2);
System.out.println("This supports Transactions : "+b1);
System.out.println("This supports SelectforUpdate : "+b2);
}
contd..
83
Example on DatabaseMetadata
(Contd.).
catch(Exception e)
{ e.printStackTrace
();
}
}
}
public class MetaDataExample {
public static void main(String args[]) {
new MakeConnection3();
}
}
84
Example on DatabaseMetadata
(Contd.).
The ResultSetMetaData
Object
ResultSetMetaData is an interface which contains methods to get information about
the
types and properties of the columns in the ResultSet object
for(int i=1;i<=noc;i++) {
System.out.print("Column "+i+" ="+rsmd.getColumnName(i)+"; ");
System.out.print("Column Type ="+rsmd.getColumnType(i)+"; ");
System.out.println("Column Type Name="+rsmd.getColumnTypeName(i)+";");
}
}
catch(Exception e)
{ e.printStackTrac
e();
}
}
}
Example on
ResultSetMetaData
public class RSMetaDataExample {
(Contd.).
public static void main(String args[]) {
new MakeConnection4();
}
}
The example shows how to use a ResultSetMetaData object to determine the following information
about the ResultSet:
The number of columns in the ResultSet.
The name of each column
The American National Standards Institute (ANSI) SQL type for each column
java.sql.Types
The java.sql.Types class defines constants that are used to
identify ANSI SQL types. ResultSetMetaData.getColumnType() returns an integer value that
corresponds to one of these constants.
Example on ResultSetMetaData
(Contd.).
Mapping Database Types to Java
Types
ResultSet maps database types to Java types.
In many cases, you can get all the columns in your result set using the getObject() or
getString() methods of ResultSet. For performance reasons, or because you want to
perform complex calculations, it is sometimes important to have your data in a type that
exactly matches the database column.
CHARACTER String
VARCHAR String
LONGVARCHA R String
NUMERIC java.math.BigDec imal
DECIMAL java.math.BigDec imal
BIT boolean Boolean
TINYINT byte Integer
SMALLINT short Integer
INTEGER int Integer
BIGINT long Long
REAL float Float
FLOAT double Double
DOUBLE PRECISION double Double
BINARY byte[]
VARBINARY byte[]
LONGVARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTA MP java.sql.Timestamp
Quiz
1. Which of the following java type is mapped to the SQL data type BIT
a) String
b) boolean
c) Int
d) byte
2. What object is returned, when you invoke the getMetaData method on the
Connection
object
a) StatementMetaData Answers
b) ResultSetMetaData :
1:
c) DatabaseMetaData
b
d) ConnectionMetaDat 2:
2
Prepared Statement Interface
[InsertPrepared.java]
• 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.
• How to get the instance of PreparedStatement?
• The prepareStatement() method of Connection interface is used to return the
object of PreparedStatement. Syntax:
• public PreparedStatement prepareStatement(String query)throws
Prepared Statement Interface
• Methods of PreparedStatement interface
• public void setInt(int paramIndex, int value)sets the integer value to the given
parameter index.
• public void setString(int paramIndex, String value)sets the String value to the
given parameter index.
• public void setFloat(int paramIndex, float value)sets the float value to the given
parameter index.
• public void setDouble(int paramIndex, double value)sets the double value to
the given parameter index.
• Exemple: PreparedStatement interface that inserts the record
• First of all create table as given below:
• create table emp(id number(10),name varchar2(50));
Prepared Statement Interface
• Example1: To search a record using prepared statement (InsertPrepared.java)
• Example2: To insert a record using prepared statement (InsertPrepared1.java)
Example 1 on
PreparedStatement
/* This class is executed in the following manner :
if you want to create the table, you will execute as java JCreate table1 where table1 is the name of the
table. The table table1 is created with the following columns empid, empname, dept, joindate, salary
*/
import java.sql.*;
class JCreate {
public static
void main(String
args[]) throws
SQLException {
JdbcCalls e = new JdbcCalls();
e.create(args);
}
}
Example 1 on
PreparedStatement(Contd.).
import java.sql.*;
class ConnectionClass {
Connection con;
Connection connectionFactory() {
try {
Class.forName("oracle.jdbc.dr
iver.OracleDriver");
con=DriverManager.getConn
ection
("Jdbc:Oracle:thin:@localhost:152
1:ORCL","scott","tiger");
}
catch(Exception e) {
System.out.println(e);
}
} return con;
Example 1 on PreparedStatement
(Contd.).
class JdbcCalls {
Connection
con;
JdbcCalls() {
ConnectionClass x = new ConnectionClass();
con=x.connectionFactory();
}
void create(String[] args) throws SQLException
{
String tablename = args[0];
PreparedStatement pst = con.prepareStatement("Create table "+tablename+" (empid
number(4), empname varchar(20), dept varchar2(10), joindate date, salary
number(10,2))");
pst.executeUpdate();
System.out.println(“Table created successfully”);
} }
Example 1 on PreparedStatement
(Contd.).
Example 2 on
PreparedStatement
/* This class is executed in the following manner :
If you want to insert a row within the table, you will execute as java JInsert jdbcdemotable 1001 anish
admin 23-dec-2008 50000.00 */
import java.sql.*;
class JInsert {
public static void main(String args[]){
try {
JdbcCalls e = new JdbcCalls();
e.insert(args);
}
catch(SQLException e)
{ System.out.println(e.toString(
));
}
}
Example 2 on PreparedStatement
(Contd.).
class JdbcCalls {
Connection
con;
JdbcCalls() {
ConnectionClass x = new ConnectionClass();
con=x.connectionFactory();
}
void insert(String[] args) throws SQLException
{
String tablename = args[0];
int empid = Integer.parseInt(args[1]);
String empname = args[2];
String dept = args[3];
String dat=args[4];
Float salary =
Example 2 on PreparedStatement
(Contd.).
PreparedStatement pst = con.prepareStatement("insert into "+tablename+"
values(?,?,?,?,?)");
pst.setInt(1, empid);
pst.setString(2, empname);
pst.setString(3,
dept); pst.setString(4,
dat); pst.setFloat(5,
salary);
pst.executeUpdate();
System.out.println(“Re
cord inserted
successfully”);
}
}
Example 2 on PreparedStatement
(Contd.).
Example 3 on
PreparedStatement
/* This class is executed in the following manner :
If you want to display all the rows, you will execute as java JDisplay jdbcdemotable
*/
import java.sql.*;
class JDisplay {
public static void main(String args[]) {
try {
JdbcCalls e = new JdbcCalls();
e.display(args);
}
catch(Exception e)
{ System.out.println
(e);
}
}
} 3
Example 3 on PreparedStatement
(Contd.).
class JdbcCalls
{ Connection
con; JdbcCalls()
{
ConnectionClass x = new ConnectionClass();
con=x.connectionFactory();
}
void display(String[] args) throws SQLException {
String tablename = args[0];
PreparedStatement pst = con.prepareStatement("select * from "+tablename);
ResultSet rs= pst.executeQuery();
while(rs.next()) {
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)+"
"+rs.getDate(4)+" "+rs.getFloat(5)); }
con.close();
Example 3 on PreparedStatement
(Contd.).
Example on Modifying the
row
/* This class is executed in the following manner :
If you want to modify a row, you will execute as Java JModify table1 1001 60000.00 where
modifying a row will allow you to change the salary
*/
import java.sql.*;
class JModify {
public static void main(String args[]) {
try {
JdbcCalls e = new JdbcCalls();
e.modify(args);
}
catch(SQLException e)
{ System.out.println(
e);
}
Example on Modifying the row
(Contd.).
class JdbcCalls {
Connection con;
JdbcCalls() {
ConnectionClass x = new ConnectionClass();
con=x.connectionFactory();
}
void modify(String[] args) throws
SQLException{
String tablename = args[0];
int empid = Integer.parseInt(args[1]);
Float sal =
Float.parseFloat(args[2]);
PreparedStatement pst = con.prepareStatement("update "+tablename+" set
salary="+sal+" where empid="+empid);
int i=
pst.executeUpdate();
} 3
Example on Deleting a
row
/* This class is executed in the following manner : If you want to delete a row, you
will
execute as java JDelete table1 1001
*/
import java.sql.*;
class JDelete{
public static
void
main(String
args[]) {
try {
JdbcCalls e = new JdbcCalls();
e.delete(args);
}
} catch(SQLException e)
} { System.out.println(
Example on Deleting a row
(Contd.).
class JdbcCalls {
Connection con;
JdbcCalls() {
ConnectionClass x = new ConnectionClass();
con=x.connectionFactory();
}
void delete(String[] args) throws SQLException {
String tablename = args[0];
int empid = Integer.parseInt(args[1]);
PreparedStatement pst = con.prepareStatement("delete from "+tablename+"
where empid="+empid);
int i= pst.executeUpdate();
con.close();
}
}
Thank You
CallableStatement Interface
• A CallableStatement is used to execute stored procedures in the database. Stored
procedures are precompiled SQL statements that can be called with parameters.
They are useful for executing complex operations that involve multiple SQL
statements.
• Syntax: To create a CallableStatement,
• CallableStatement cstmt = con.prepareCall("{call ProcedureName(?, ?)}");{call
ProcedureName(?, ?)}: Calls a stored procedure named ProcedureName with
placeholders ? for input parameters.
• Methods to Execute:
• execute(): Executes the stored procedure and returns a boolean indicating whether the result
is a ResultSet (true) or an update count (false).
• executeQuery(): Executes a stored procedure that returns a ResultSet.
• executeUpdate(): Executes a stored procedure that performs an update and returns the
number of rows affected.
CallableStatement Interface
• A CallableStatement is used to execute stored procedures in the database. Stored
procedures are precompiled SQL statements that can be called with parameters.
They are useful for executing complex operations that involve multiple SQL
statements.
• Syntax: To create a CallableStatement,
• CallableStatement cstmt = con.prepareCall("{call ProcedureName(?, ?)}");{call
ProcedureName(?, ?)}: Calls a stored procedure named ProcedureName with
placeholders ? for input parameters.
• Methods to Execute:
• execute(): Executes the stored procedure and returns a boolean indicating whether the result
is a ResultSet (true) or an update count (false).
• executeQuery(): Executes a stored procedure that returns a ResultSet.
• executeUpdate(): Executes a stored procedure that performs an update and returns the
number of rows affected.
Stored Function Vs Procedures
S.NO Function Procedure
Functions always return a value after the execution of The procedure can return a value using “IN OUT” and “OUT”
1.
queries. arguments.
Each and every time functions are compiled they provide Procedures are compiled only once but they can be called many
3.
output according to the given input. times as needed without being compiled each time.
4. A Function can not return multiple result sets. A procedure is able to return multiple result sets.
5. The function can be called using Stored Procedure. While procedures cannot be called from function.
6. A function used only to read data. A procedure can be used to read and modify data.
The return statement of a function returns the control and While the return statement of the procedure returns control to
7.
function’s result value to the calling program. the calling program, it can not return the result value.
8. The function does not support try-catch blocks. Procedure supports try-catch blocks for error handling.
9. A function can be operated in the SELECT statement. While it can’t be operated in the SELECT statement.
In functions, we can use only a table variable. Temporary In procedures, we can use temporary tables or table variables to
11.
tables can not be created in function. store temporary data.
Function Example
• To define a stored procedure or function, use CREATE PROCEDURE or CREATE FUNCTION
respectively:
SHOW FUNCTION STATUS WHERE db = 'your_databasename';
DELIMITER &&
CREATE FUNCTION cal ( a int,b int) CREATE FUNCTION
RETURNS INT
func_name (parameters)
DETERMINISTIC
RETURNS
BEGIN
return a+b;
return_type
END&& BEGIN
DELIMITER ; -- function body
-- call the addition function
SELECT cal(10, 12);
END;
Function Example
DELIMITER &&
CREATE FUNCTION Func_Cube ( Num INT )
RETURNS INT
--DETERMINISTIC
BEGIN
DECLARE TotalCube INT;
SET TotalCube = Num * Num * Num;
RETURN TotalCube;
END&&
DELIMITER ;
-- call the addition function
SELECT Func_Cube(12);
Function Example
Create a table salary with sal attribute
Insert 4-5 records into salary table
Create a function which will show the average salary for the given employees
DELIMITER //
CREATE FUNCTION Demoavg() RETURNS INT
DETERMINISTIC
BEGIN
DECLARE result INT;
SET result = (SELECT AVG(marks) FROM studinfo);
RETURN result;
END //
DELIMITER ;
Now to show the avg salary we can call
Select Demoavg()
Stored Procedures
DELIMITER && IN parameter
CREATE PROCEDURE procedure_name It is the default mode. It takes a parameter as input,
[[IN | OUT | INOUT] parameter_name dat such as an attribute. When we define it, the calling
atype [, parameter datatype]) ] program has to pass an argument to the stored
BEGIN procedure. This parameter's value is always protected.
OUT parameters
Declaration_section It is used to pass a parameter as output. Its value can be
Executable_section changed inside the stored procedure, and the changed
END && (new) value is passed back to the calling program. It is
noted that a procedure cannot access the OUT
DELIMITER ;
Commands : parameter's initial value when it starts.
SHOW PROCEDURE STATUS; INOUT parameters
SHOW FUNCTION STATUS; It is a combination of IN and OUT parameters. It
Help show means the calling program can pass the argument, and
SHOW PROCEDURE STATUS WHERE
Db = DATABASE() AND Type = 'PROCEDURE'
the procedure can modify the INOUT parameter, and
then passes the new value back to the calling program.
CALL procedure_name ( parameter(s))
Stored Procedures
DELIMITER && DELIMITER && DELIMITER &&
CREATE PROCEDURE CREATE PROCEDURE CREATE PROCEDURE
get_merit_student () display_max_mark (OUT display_marks (INOUT var1 INT)
BEGIN highestmark INT) BEGIN
BEGIN SELECT marks INTO var1
SELECT * FROM studinfo SELECT MAX(marks) INTO FROM studinfo WHERE id = var1;
WHERE marks > 70;
highestmark FROM studinfo;
SELECT COUNT(id) AS END && END &&
Total_Student FROM studinfo; DELIMITER ; DELIMITER ;
END &&
DELIMITER ; Call display_max_mark SET @M = '3';
CALL display_marks(@M);
Call get_merit_student(); (@m); SELECT @M;
Show @m;
Stored Procedures
DELIMITER &&
Demonstrate Callable2.java
Stored Procedures
DELIMITER &&
CREATE PROCEDURE getmark (IN var1 INT)
BEGIN
SELECT * FROM studinfo LIMIT var1;
SELECT COUNT(id) AS Total_Student FROM studinfo where marks>var1;
END &&
DELIMITER ;
How to invoke the getmark procedure in mysql
Call procedure(val)
How to drop the procedure in mysql
Demonstrate Callable.java
Drop procedure procedurename
UNIT:2 Web Architecture
Introduction to HTML
• HTML (HyperText Markup Language) is the standard markup language used to
create web pages. It defines the structure of a web page using a series of
elements and tags. HTML elements are the building blocks of all websites, and
they allow browsers to interpret and display content.
UNIT:2 Web Architecture
<!DOCTYPE html>
•<!DOCTYPE html>: Defines the document
<html> type and version of HTML.
<head> •<html>: The root element of the HTML
<title>Page Title</title> document.
•<head>: Contains meta-information about
</head> the document, such as the title, links to
<body> stylesheets, and scripts.
•<title>: Sets the title of the document,
<h1>This is a Heading</h1>
displayed in the browser's title bar or tab.
<p>This is a paragraph.</p> •<body>: Contains the visible content of the
</body> document.
</html>
UNIT:2 Web Architecture
Various HTML Tags and Their Usage
HTML tags are used to define elements within a webpage. Below are some of the most common tags
and their purposes:
Heading Tags (<h1> to <h6>): Define headings of different levels.
<h1>Main Heading</h1><h2>Subheading</h2>
Paragraph Tag (<p>): Defines a paragraph.
<p>This is a paragraph of text.</p>
Link Tag (<a>): Defines a hyperlink.
<a href="https://example.com">Visit Example</a>
Image Tag (<img>): Embeds an image.
<img src="image.jpg" alt="Description of image">
UNIT:2 Web Architecture
List Tags:
Unordered List (<ul>) and List Item (<li>): <dl>
• <ul style="list-style-type:disc;"> <ol type="I“start="50"> <dt>Coffee</dt>
<li>Coffee</li> <li>Coffee</li> <dd>- black hot drink</dd>
<li>Tea</li> <li>Tea</li> <dt>Milk</dt>
<li>Milk</li> <li>Milk</li> <dd>- white cold drink</dd>
</ul> </ol> </dl>
Bold and Italic Tags:
Bold Text (<b> or <strong>):
<b>This text is bold</b>
Italic Text (<i> or <em>):
<i>This text is italicized</i>
UNIT:2 Web Architecture
Layout Tags :Layout tags help structure and Semantic Tags : Semantic tags clearly
organize content on the web page. describe the meaning of the content they
enclose. These tags improve the readability of
<div> Tag: Defines a division or section of the the HTML and provide better accessibility and
page, commonly used for layout purposes. SEO benefits.
<div> This is a section of the page.</div> <header>: Defines a header for a
<span> Tag: Used to group inline elements for document or section.
styling. <nav>: Defines navigation links.
<span style="color: red;">This text is red.</span> <article>: Defines an article or piece of
content that could stand alone.
<div style="background- <section>: Defines a section in a
color:black;color:white;padding:20px;"> document.
<h2>London</h2> <aside>: Defines content aside from the
main content (like a sidebar).
<p>London is the capital city of England</p>
<footer>: Defines a footer for a document
</div> div { width:300px; margin:auto; } or section.
UNIT:2 Web Architecture
Example:
html <section>
<article>
Copy code <h2>Article Title</h2>
<header> <p>This is the main content of the
<h1>Website Title</h1> article.</p>
</header> </article>
</section>
<nav> <aside>
<ul> <p>This is related content, such as ads or
<li><a href="#home">Home</a></li> links.</p>
<li><a href="#about">About</a></li> </aside>
<footer>
</ul> <p>Footer content goes here.</p>
</nav> </footer>
UNIT:2 Web Architecture
Tables :
Example:
Tables are used to organize data in rows and columns. <table border="1">
<table>: Defines the table structure. <tr>
<tr>: Defines a row in the table. <th>Name</th>
<th>: Defines a header cell in the table. <th>Age</th>
</tr>
<td>: Defines a standard cell in the table. <tr>
<td>John</td>
<td>25</td>
</tr>
<tr>
<td>Jane</td>
<td>30</td>
</tr>
</table>
UNIT:2 Web Architecture
HTML FORMS: <form action="/submit" method="post">
<label for="name">Name:</label>
• <form>: Defines the form.
<input type="text" id="name"
• <input>: Defines an input field. name="name"><br><br>
• <textarea>: Defines a multi-line text
input field. <label for="age">Age:</label>
<input type="number" id="age"
• <button>: Defines a clickable name="age"><br><br>
button.
• <select> and <option>: Defines a <label for="gender">Gender:</label>
dropdown list. <select id="gender" name="gender">
<option value="male">Male</option>
<option value="female">Female</option>
</select><br><br>
<button type="submit">Submit</button>
</form>
UNIT:2 Web Architecture
STYLING HTML (USING STYLE)
You can add inline styles to HTML elements using the style attribute or link to
external stylesheets.
Inline CSS:
<p style="color: blue; font-size: 14px;">This is a styled paragraph.</p>
External CSS:
<link rel="stylesheet" type="text/css" href="styles.css">
UNIT:2 Web Architecture
USING DIV FOR LAYOUT:
The <div> tag is often used for creating layouts, especially with CSS.
Example:
<div style="width: 100%; background-color: lightgray;">
<div style="width: 50%; float: left;">
Left Column Content
</div>
<div style="width: 50%; float: right;">
Right Column Content
</div>
</div>
HTML
Application
Tags
13
Objectives
At the end of this module, you will be able to:
Table creation
Form creation
Frames and usage
wipro.co
13
HTML
Tables
13
Application Tags:
Tables
Tables are used to display text / Information in tabular format. I.e. in the from of rows and
columns.
Tags Purpose
13
Tables: Table Attributes
ALIGNMENT Left / center / right
EXAMPLE:
13
Tables: Merging
Cells
1. ROWSPAN
2. COLSPAN
13
Demonstration
Demonstration of creating different tables that use the following attributes :
cellspacing
cellpadding
rowspan
colspan
table border
14
Exampl
e
EXAMPLE:
<TABLE BORDER="7" CELLPADDING="7" CELLSPACING="10">
<TR BGCOLOR="#00FF00">
<TD>A green row.</TD>
<TD BGCOLOR="#FFFF00">This cell should be yellow, overriding the
row color.</TD> <TD>Back to the row color.</TD>
<TR BGCOLOR="#0000FF">
<TD>A blue row.</TD>
<TD><PRE> </PRE></TD>
<TD ROWSPAN="2">This cell takes the color of the topmost row that
it spans</TD>
</TR>
<TR BGCOLOR=“#FF0000">
<TD colspan=“2” align=“center” >A red row.</TD>
</TR>
</TABLE>
14
Quiz
1. What are the two table dimension tags?
a. <TL> and TW>
b. <TR> and <TD>
c. <TD> and <RD>
<TR> and
<TD>
14