Untitled - Javasiva

advertisement
Easy JavaWeb
About The Author
I am Sivaramayya Madhupada, Sun Certified Professional. I have been working for
Miracle Software Systems since 2005 as a Sr.Technical Manager. Before coming to
work at Mracle, I worked for more than two years
as a C & J2EE faculty in CMC and Technical Head in
Logix Software Solutions. I used to give guest
lecturers in many institutions and engineering & PG
colleges. Basically, I spend a lot of my time helping
people be successful with the C & Java/J2EE coding.
This book is a reflection of what I do every day. The
book within covers topics and exercises that I see
people struggling with every day.
I spend the bulk of my time working with C, Java,
J2EE technologies,IBM tools like Webpshere Portals,
Websphere Commerce, Websphere Message
Broker, Rational Application Developer, Rational Software Architect, DB2 and etc.
Over the last 9 years, I have played many of the roles like Project Lead, Practice
Manager, Member of Center Of Excellence, Project Manager, and Currently as
Sr.Technical Manager. I’ve worked on many domain (education, telecom, health
insurance, logistics and etc) projects—successful ones as well as complete failures. I
have worked with many resources. Some of them are lacking
fundamental
Programming skills, but I never find enough good time to spend with them. So I had
thought of starting this kind of book to give good fundamental programming
techniques in terms of education and industry approaches.
When I am doing my master’s in computer science in Andhra University’s College, I
used to take the classes and seminars in the class. When I am eagerly waiting for
sharing my knowledge and experience, Miracle Software Systems has started an
engineering college “Miracle Educational society“ to produce world class
professionals. I have used this chance to convert my thoughts into physical form by
teaching C and Java.
Presently I am maintaining a website www.javasiva.in for technical education which
is helping many students related to computer science subjects. It is purely targeted
to B.Tech, MCA other computer science related students of all universities.
Many of IT students/Professionals reading my Easy C&DS,Easy Java, Easy JavaWeb
and Easy J2EE books. I am writing two more books with the below titles.
Easy Android
Easy Oracle
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 2 of 155
Easy JavaWeb
Target of This Book
This book is targeted to support the students and software engineers. I have written
this book to learn and understanding Webtechnologies using Java.It requires strong
knowledge on OOPS Concepts, Java Concepts and Application Development
Concepts.
There are many good books from good authors available in the market and they
have explained the things clearly. But there is no bridge between topics to topic to
go to the next level of reading. And to learn WebTechnologies using java, we need
to refer many books for some topics. They are throwing a lot of theory and less
appropriate scenario’s/examples. It is completely time consuming process. This is
really irritating the student and developer communities.
Academic syllabuses are not allowing the students to meet the market requirement
properly. At the time of academics, it is somewhat difficult to prepare for industry;
because it is a separate path. Students are unable to concentrate on both academic
and industry paths simultaneously.
Industry professionals are missing their deadlines and unable to give good
productivity because of lacking of strong fundamental programming skills, and may
be lack of understanding the system.
Industries working experience in many projects with different roles,
Expertism on Java/J2EE technologies and IBM tools, working with many
different level of professionals, good track record in teaching experience
and working with many students from many colleges are given me an
alert that what is that the Professionals/Students are really looking for.
I have taken lot of care to align academic and industry paths into a single path to
meet requirements like how much content is sufficient for writing examinations
without having any confusion and what is that the industry is looking from students
or professionals.
I have designed this book for students and IT professional in such a way that they
can survive with this book to get good fundamental web programming skills.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 3 of 155
Easy JavaWeb
Acknowledgment
One of the great pleasures of writing Easy JavaWeb and acknowledges the efforts
of many people whose names may not appear on the cover, but their hard work,
cooperation, friendship and understanding the situations are invested to complete
this book smoothly.
I would like to thank many people for helping me to complete this book. First; I
would like to convey my very special thanks to MCA/B.Tech students who have
encouraged me a lot. This book would not be there without them.
I would like to thank Srinivas Rao Bora (Senior Technical Associate, MSS) and
Chandrasekhar Kota (Team Lead, MSS) for their work making me to write “Easy
JavaWeb”. If you enjoy the flow of the sections, contents, and the clarity, then that
is probably in some part due to tehm. I have started writing this book since the year
2008.
I would like to thank to Mr.Prasad V Lokam, CEO, and MSS. When he is having free
time, he used to look at technical, project discussions and training. He used to tell
that “don’t throw much theory and learn by examples”. I have started this book with
this motto only. I have learned many things from him like the way he is articulating
the things.
I am eager to convey my special thanks to Mr.Arjuna Rao A,Prinicipal,MES and
Ms.Madhavi Lokam,Chairman,MES and entire MES Team.I am very thankful to
Mr.Sankar Sastry Matta,Asst Professior,MES for his heartful support.
Last but not least, I would like to convey my heartfelt thanks to my family members
for their patience and bearing problems with me.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 4 of 155
Easy JavaWeb
Preface
Industry working experience on different dominas using different java/J2EE
technologies, IBM tools and teaching of C and JAVA/J2EE motivated me to write this
book. It is targeted to support the students and software engineers.It will help you to
understand Advanced Java Programming concepts like HTML, CSS, JavaScritp, XML
AJAX, JDBC, Servlets, JSP, Custom Tags, and many advanced topics with
programmatic examples and pictorial explanations.
This book “Easy JavaWeb” addressed many problems and their solutions provided in
terms of algorithms and programming examples.This book contains scenario’s which
are reflecting the real time scenario’s. Students/Programmer/Developer tends to do
lots of mistakes while coding.This book providing “Points to remember” section to
alert the programmers not do any coding mistakes.This book contains many
exercises for each possible topic and you can see answers in next version.
You are having a good opportunity to learn advanced topics in java and J2EE
technologies by learning Easy Java, Easy JavaWeb and Easy J2EE books.
Now onwards, you will get more information from www.javasiva.in related to C&DS,
JAVA, Web technologies, DBMS and all universities B.Tech & MCA courses also. I am
expecting some important points from your side that are missing in this book like any
mistakes, readability problems and etc...Please write all your feedback to my email
and I will inject them to improve our book in all aspects. Thanks to all of my students
and Professors in advance for their support to write this book. The motto of this book
is to give good programming knowledge to meet industry requirements.
I have written some content which is somewhat simulated to many good sites and
their style of articulating the things were adapted. The definition of various software
engineering
terms
and
concepts
were
adapted
from
Wikipedia
(http://wikipedia.org/).
Prerequisites:Before start reading this book, please make sure that your system get
installed with JDK5.0/6.x, Netbeans5.5/6.x, Eclipse, and any application server like
GlassFish/Websphere
Application
server
and
any
database
like
IBMDB2/Oracle10g/MySQL. The most of the programs and concepts required JDK5.0
version.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 5 of 155
Easy JavaWeb
Table of Contents
1.
HTML------------------------------------------------------------------------------------------ Error! Bookmark not defined.
1.1. Un Ordered List ------------------------------------------------------------------- Error! Bookmark not defined.
1.2. Ordered List ------------------------------------------------------------------------ Error! Bookmark not defined.
1.3. Definition List ---------------------------------------------------------------------- Error! Bookmark not defined.
1.4. Color and Image ------------------------------------------------------------------ Error! Bookmark not defined.
1.5. Linking ------------------------------------------------------------------------------ Error! Bookmark not defined.
1.6. Complex HTML Forms----------------------------------------------------------- Error! Bookmark not defined.
1.7. Tables ------------------------------------------------------------------------------- Error! Bookmark not defined.
1.8. Frames ------------------------------------------------------------------------------ Error! Bookmark not defined.
2.
CSS -------------------------------------------------------------------------------------------- Error! Bookmark not defined.
2.1. Types Of Styles ------------------------------------------------------------------- Error! Bookmark not defined.
3.
XML -------------------------------------------------------------------------------------------- Error! Bookmark not defined.
3.1. XML Validation -------------------------------------------------------------------- Error! Bookmark not defined.
3.2. XML Processing------------------------------------------------------------------- Error! Bookmark not defined.
4.
XHTML --------------------------------------------------------------------------------------- Error! Bookmark not defined.
5.
Javascript ---------------------------------------------------------------------------------- Error! Bookmark not defined.
5.1. Data Types & Variables --------------------------------------------------------- Error! Bookmark not defined.
5.2. Control Structures ---------------------------------------------------------------- Error! Bookmark not defined.
5.3. Arrays ------------------------------------------------------------------------------- Error! Bookmark not defined.
5.4. Functions --------------------------------------------------------------------------- Error! Bookmark not defined.
5.5. Windows Events ------------------------------------------------------------------ Error! Bookmark not defined.
5.6. String Handling -------------------------------------------------------------------- Error! Bookmark not defined.
6.
JDBC ----------------------------------------------------------------------------------------------------------------------------- 9
6.1. Loading The Driver -------------------------------------------------------------------------------------------------- 9
6.2. Getting a Connection With The Database ---------------------------------------------------------------- 11
6.3. Executing Statements -------------------------------------------------------------------------------------------- 13
6.4. JDBC Programs Using Netbeans------------------------------------------------------------------------------ 15
6.5. Getting Result ------------------------------------------------------------------------------------------------------- 19
6.6. Calling Procedures & Functions ----------------------------------------------------------------------------------- 23
6.7. Scrollable & Updatable ResultSets -------------------------------------------------------------------------- 25
6.8. Transactions --------------------------------------------------------------------------------------------------------- 32
7.
Servlets ---------------------------------------------------------------------------------------------------------------------- 34
7.1. CGI ---------------------------------------------------------------------------------------------------------------------- 34
7.2. Tomcat Server ------------------------------------------------------------------------------------------------------ 35
7.3. WebApplication ----------------------------------------------------------------------------------------------------- 36
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 6 of 155
Easy JavaWeb
7.4. Deployment of Webapplication ------------------------------------------------------------------------------------ 37
7.5. Servlet Life Cycle -------------------------------------------------------------------------------------------------- 39
7.6. Servlet API ----------------------------------------------------------------------------------------------------------- 40
7.7. Servlet Artchitecture---------------------------------------------------------------------------------------------- 42
7.8. Request Processing ----------------------------------------------------------------------------------------------- 42
7.9. Creating a Servlet ------------------------------------------------------------------------------------------------- 43
8.
7.10.
Creating Application Using NetBeans------------------------------------------------------------------- 45
7.11.
Reading Data From HTML Form -------------------------------------------------------------------------- 51
7.12.
Session Tracking/State Programming------------------------------------------------------------------ 53
7.13.
HttpSession ------------------------------------------------------------------------------------------------------ 56
7.14.
Cookie -------------------------------------------------------------------------------------------------------------- 59
7.15.
ServletConfig ---------------------------------------------------------------------------------------------------- 61
7.16.
ServletContext -------------------------------------------------------------------------------------------------- 63
7.17.
Inter Servlet Communication/ Collaboration -------------------------------------------------------- 64
7.17.1. redirect vs forward ------------------------------------------------------------------------------------ 66
7.18.
E-Commerce Project ------------------------------------------------------------------------------------------ 67
7.18.1. Setting a Default page for an Application ---------------------------------------------------- 77
7.19.
Change Salary Project --------------------------------------------------------------------------------------- 78
7.20.
File Uploading --------------------------------------------------------------------------------------------------- 88
7.21.
Filters --------------------------------------------------------------------------------------------------------------- 90
7.22.
Listeners----------------------------------------------------------------------------------------------------------- 92
7.23.
Servlet Security Issues -------------------------------------------------------------------------------------- 94
JSP ------------------------------------------------------------------------------------------------------------------------------ 95
8.1. JSP Phases and Life Cycle -------------------------------------------------------------------------------------- 97
8.2. Anatomy/Structure of a JSP Page --------------------------------------------------------------------------- 98
8.3. JSP Elements -------------------------------------------------------------------------------------------------------- 98
8.4. Implicit Obects ----------------------------------------------------------------------------------------------------- 100
8.5. Creating Webapplication using Eclipse-------------------------------------------------------------------- 102
8.6. Exception Handling ----------------------------------------------------------------------------------------------- 110
8.7. Session Tracking/State Programming--------------------------------------------------------------------- 111
8.8. HttpSession/session --------------------------------------------------------------------------------------------- 113
8.9. Cookie ----------------------------------------------------------------------------------------------------------------- 115
9.
8.10.
Includes and Forwards -------------------------------------------------------------------------------------- 117
8.11.
JavaBeans ------------------------------------------------------------------------------------------------------- 119
8.12.
Accessing Database from JSP ---------------------------------------------------------------------------- 122
8.13.
E-Commerce Project ----------------------------------------------------------------------------------------- 123
8.14.
Users Info From XML ---------------------------------------------------------------------------------------- 131
8.15.
Memory Usage Considerations--------------------------------------------------------------------------- 134
8.16.
JSP Application Using MVC -------------------------------------------------------------------------------- 135
Custom Tags ---------------------------------------------------------------------------------------------------------------- 139
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 7 of 155
Easy JavaWeb
9.1. Tag Life Cycle ------------------------------------------------------------------------------------------------------ 139
9.2. Tag with attributes ----------------------------------------------------------------------------------------------- 142
9.3. Tags With Body ---------------------------------------------------------------------------------------------------- 144
9.4. Tags With Iterations --------------------------------------------------------------------------------------------- 146
10. AJAX --------------------------------------------------------------------------------------------------------------------------- 148
10.1.
XMLHttpRequest----------------------------------------------------------------------------------------------- 148
10.2.
Working With Text-------------------------------------------------------------------------------------------- 150
10.3.
Working With XML -------------------------------------------------------------------------------------------- 152
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 8 of 155
Easy JavaWeb
1.
JDBC
This feature of Java allows a java program to connect with the Enterprise Information System(
database) such as Oracle,DB2,MySQL, SQL server etc., to perform Database transactions.In order to
connect from a java program to the backend database a special program is required which is k nown
as a driver.
Database Architectures: Java supports Two-tier, Three-tier and N-tier architectures.
Application
JDBC
Driver
EIS
Here the application is java code which calls JDBC library.
JDBC loads a driver.
Driver talks to a particular database.
Can have more than one driver -> more than one database.
Can change database engines without changing any application code.
From the above discussion,we can say that The JDBC API contains two major sets of interfaces: the
first is the JDBC API for application writers, and the second is the lower-level JDBC driver API for
driver writers. JDBC technology drivers fit into one of four categories. Applications and servlets can
access databases via the JDBC API using any of JDBC technology-based drivers.
java.sql package : This containing the following interfaces and classes for managing database
transactions.Some advanced classes and interfaces will be available in javax.sql package and will be
discussed later.
classes
Interfaces
DriverManager
Connection
Class (It is from java.lang package)
Statement
PreparedStatement
CallableStatement
ResultSet
ResultSetMetaData
DatabaseMetaData
To work with any Enterprise Information System, we need to follows the below 4 stpes.
1.1. Loading The Driver
The driver should be loaded into the memory before getting a connection.The Class.forName( )
or DriverManager.registerDriver() will be used to load the driver.Driver will establishes the
contract between Java and vendor specific database.Here I am trying to explain four drivers.The
drivers are divided into 4 categories named as type1, type2, type3, type4.
a.
Type1: JDBC ODBC Bridge Drivers
Use bridging technology.
This driver will be installed with jdk.
Requires installation/configuration on client machines.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 9 of 155
Easy JavaWeb
Not good for Web.
e.g. ODBC Bridge.
b.
Type2: Part Java Part Native Drivers
Native API driver.
Requires installation/configuration on client machines.
Used to leverage existing CLI libraries.
e.g. Intersolv Oracle Driver, WebLogic drivers.
c.
Type3: Intermediate Database Access Server Drivers/Middleware
Calls middleware server, usually on database host.
A three tier solution.
Very flexible -- allows access to multiple databases using one driver.
Only need to download one driver.
But it’s another server application to install and maintain.
e.g. Symantec DBAnywhere.
d.
Type4: Pure Java / Thin Drivers
100% Pure Java Driver.
No additional transformation or middleware layers, therefore has high performance.
Use Java networking libraries to talk directly to database engines.
e.g. Oracle, mSQL.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 10 of 155
Easy JavaWeb
Out of four drivers, type1 and type2 are will be used commonly and got popularity.So Here I
am giving details about these only.
Loading Type1 Driver: This driver requires datasource name of a database.
Creating a Data Source Name (DSN): go to control panelAdministrative Toolsclick
datasources(ODBC) in the userDSN tab, click on the ADD button, which displays a list of
the installed drivers and then select the required driver, for ex. MicrosoftODBC for oracle,
click on Finish button and specify a name for the data source, for ex. Javaoracle.Below is
the method to load the driver.
Syntax: static Class forName( String class-name ) throws ClassNotFoundException
Ex:
Class.forName( “sun.jdbc.odbc.JdbcOdbcDriver” );
Driver class name
The above driver is type1 driver which is common to all vendor databases.
Loading Type4 Driver: Below I am listing
drivers.
out some of well known database’s type4
Ex: Class.forName("COM.ibm.db2.jdbc.net.DB2Driver"); //for DB2
Ex: Class.forName("oracle.jdbc.driver.OracleDriver");
//for Oracle
Ex: Class.forName("com.mysql.jdbc.Driver");
//for MySQL
Note: Before working with type4 or pure java driver, we need to specify the location of
respective vendor database jar in the classpath like below.
set classpath=existedclasspath;location of jar file;
Ex: C:\>set classpath=.;c:\classes111.jar;
(This jar for Oracle).
1.2. Getting a Connection With The Database
The following methods of DriverManager class can be used for opening connections with the
database and following are the methods to get connection object.
1.
public static Connection getConnection( String url ) throws SQLException
2.
public static Connection getConnection( String url, String uname, String pwd )
SQLException
throws
Here We can use any of the vendor database url(IP address of database server/name of the
server,username and password).
Connection: It is an Interface which manages a connection with the database and below are
the some of important methods oftenly used.
Statement createStatement( ): Creates a statement. A statement is used for
executing SQL statements against the database.
PreparedStatement prepareStatement(String sql statement): It
takes a
query and compiles the query. It can be used for executing any number of times of
compiled query.We can supply values to the query by mapping actual values to
place holders(?).It is a good object to improve the efficiency of the application
because it will stop compiling the SQL statement every time in database.
CallableStatement
prepareCall (String sql statement):Prepares a callable
statement, which is used for executing stored procedures of the database.
void commit( ) : Makes the changes permanent.
void rollback( ) : Moves the cursor to the last saved position.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 11 of 155
Easy JavaWeb
void setAutoCommit( Boolean autocommit ) : Sets on or off the auto commit,
default is true means whatever the statements are executed in database will be
commited automatically.If we don’t want to happen like that we can use
setAutoCommit(false).So this method will be useful in transactions.
DatabaseMetaData getMetaData( ) :
contains the details of the connection.
Returns the DatabaseMetaData which
void close ( ) : Closes the connection.
Example
For
Type1:
Connection
“jdbc:odbc:javaoracle”, ”scott”, “tiger” );
con=
DriverManager.getConnection(
Here “ tiger “ is the password , “ scott “ is user name , “ javaoracle “ is the data source
name created in the control panel.
The above url is common to all vendor databases.Below I am listing
known database’s url’s.
out some of well
Example For Type4: Connection con= DriverManager.getConnection
("jdbc:oracle:thin:@localhost:1521:ORCL" , "scott", "tiger");// for Oracle
Here “localhost” refers the oracleserver name, 1521 is the port to listen request,ORCL is the
servicename or SID,scott is username and tiger is password.
Example For Type4: Connection con=
DriverManager.getConnection("jdbc:db2://10.0.57.86:6789/Test", ”admin",”admin");
//For DB2
Example For Type4: Connection con=
DriverManager.getConnection("jdbc:mysql://localhost:3306/Test", "root", "admin");
//for MySQL
Example1:Checking whether the java is connecting to oracle properly or not(using type1).
import java.sql.*;
class testcon
{
public static void main(String args[ ])
{
try
{
Connection con=null;
System.out.print("Loading Driver ..... ");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println(" OK ");
System.out.print("Getting Connection ..... ");
con= DriverManager.getConnection("jdbc:odbc:javaoracle","scott","tiger");
System.out.println(" OK ");
con.close( );
}
catch(ClassNotFoundException ex)
{
System.out.println("Driver Not Loaded");
}
catch(SQLException ex)
{
System.out.println("SQL Error: "+ex);
}
}
}
Example2:Checking whether the java is connecting to oracle properly or not(using type4).
import java.sql.*;
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 12 of 155
Easy JavaWeb
class testcon
{
public static void main(String args[ ])
{
try
{
Connection con=null;
System.out.print("Loading Driver ..... ");
Class.forName("oracle.jdbc.driver.OracleDriver");
System.out.println(" OK ");
System.out.print("Getting Connection ..... ");
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott",
"tiger");
System.out.println(" OK ");
con.close( );
}
catch(ClassNotFoundException ex)
{
System.out.println("Driver Not Loaded");
}
catch(SQLException ex)
{
System.out.println("SQL Error: "+ex);
}
}
}
Note:To execute the above program, we need to set the classpath for respective database
jar.
1.3. Executing Statements
For executing the SQL statements against the database, First we get a Statement object from
our DB Connection object(Please refer Geconnection section).we will use A Statement object is
used to send SQL statements to the DB.The below are some of the important methods oftenly
used.
boolean execute( String sql-statement ): Most of the programmers will use this
method for executing DDL and PL/SQl procedure.It executes any SQL statement,
returns true if a select statement is executed, it returns false for a non-select statement.
ResultSet executeQuery( String select-statement ): Executes the given select
statement and returns the result set which contains the selected records.
int executeUpdate( String dml-statement ): Executes the given DML statement and
returns the no. of records that are effected from the execution.
Int[] executeBatch():JDBC 2.0 allows batch updates multiple statements can be
executed as a single batch we can roll back the whole batch if a single statement fails
We simply add statements to be batched to a Statement or PreparedStatement object
using addBatch(). We can remove the statements using clearBatch().Executes the given
multiple DML statement and returns the no. of records that are effected from the
execution.
void close( ): Closes the statement and it is better to assign null to the object for
garbage collection.
Example3:Create a table in Oracle.
import java.sql.*;
public class testcon {
public static void main(String a[]) {
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//loading driver
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 13 of 155
Easy JavaWeb
con = DriverManager.getConnection("jdbc:odbc:javaoracle", "scott", "tiger");//getting
connection
/*
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott",
"tiger"); */
Statement st = con.createStatement();
st.execute("create table mesmca(sno number(4),sname varchar2(25))");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Example4:Insert a row in a table in Oracle.
import java.sql.*;
public class testcon {
public static void main(String a[]) {
Connection con = null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//loading driver
con = DriverManager.getConnection("jdbc:odbc:javaoracle", "scott", "tiger");//getting
connection
Statement st = con.createStatement();
int i = st.executeUpdate("insert into mesmca values(2,'siva')");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Example5:Create a table in DB2.
import java.sql.*;
class CreateProductTable {
public static void main(java.lang.String[ ] args) {
try
{
Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" );
String url = "jdbc:db2://10.0.52.86:6789/Test";
Connection con = DriverManager.getConnection(url,”admin", "db2admin");
Statement statement = con.createStatement();
String
createProductTable
=
"CREATE
TABLE
PRODUCT(NAME
VARCHAR(64),ID
VARCHAR(32) NOT NULL,PRICE FLOAT,DESC VARCHAR(256),PRIMARY KEY(ID))”;
statement.executeUpdate( createProductTable );
} catch( Exception e ) { e.printStackTrace(); }
}
}
Example6:Insert a row in a table in DB2.
import java.sql.*;
class InsertProducts {
public static void main(java.lang.String[ ] args) {
try
{
Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" );
String url = "jdbc:db2://10.0.52.86:6789/Test";
Connection con = DriverManager.getConnection( url, "db2admin", " db2admin " );
Statement statement = con.createStatement();
statement.executeUpdate("INSERT INTO PRODUCT VALUES('EasyJavaWeb','4', 100.00,
'A good introduction to J2EE')" );
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 14 of 155
Easy JavaWeb
con.close();
statement.close();
}catch( Exception e ) { e.printStackTrace(); }
}
}
Example7:Insert a row in a table in oracle using PreparedStatement.
import java.sql.*;
public class propstat {
public static void main(String a[]) {
String sname = a[0];
int sno = Integer.parseInt(a[1]);
Connection con = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott",
"tiger");
PreparedStatement ps = con.prepareStatement("insert into mesmca values(?,?)");
ps.setInt(1, sno);
ps.setString(2, sname);
int c = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Example8:Inserting multiple rows in a table in oracle using executeBatch() .
import java.sql.*;
public class first {
public static void main(String a[]) {
Connection con = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott",
"tiger");
Statement st = con.createStatement();
st.addBatch("insert into mesmca values(6,'Rajasri')");
st.addBatch("insert into mesmca values(5,'Santhosh')");
int i[] = st.executeBatch();
} catch (Exception e) {
e.printStackTrace();
}
}
}
1.4. JDBC Programs Using Netbeans
IDE: stands for Integrated Development Environment and it is place where all tools are
available to speed up the development process. They will never do anything extra and they will
just help us to develop the application with a great speed.They will provide
Source editor
Compiler/Interpreter
Debugger
Build Automation Tools
Version Control integration
There are many number of IDE’s are available in the market, but the Netbeans is the best IDE
to develop the application and it provides flexible tooling also.
Step 1: We have to open the netbeans first.In menu go to startPrograms and then click on
NetBeans IDE Or directly click on icon available on desktop and Then you will get below screen
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 15 of 155
Easy JavaWeb
Step 2: We have to create a new project by going to File NewProject then will get below
screen. Then select java in Categories and then select Java Application in Projects section.
Step 3: Click Next, then will get below screen. Then provide the values for Project Name and
Project Locations like below. Click Finish.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 16 of 155
Easy JavaWeb
Step 4: Create a class by selecting the newly created projectNewJava Class like below first
figure.
When you click on “Java Class”
package.Click Finish.
then we will get below screen.Now Provide the Class Name in and
Note: Here We should not specify the extension of java file (.java) and it will be appended
automatically by IDE.
Type the below code in source editor of netbeans.
package com.javasiva.ajp;
import java.sql.*;
public class InsertRecord {
public static void main(String a[]) {
int sno = 125;
String sname = "Ramayya";
Connection con = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl",
"scott", "tiger");
PreparedStatement
ps
=
con.prepareStatement("insert
into
mesmca
values(?,?)");
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 17 of 155
Easy JavaWeb
ps.setInt(1, sno);
ps.setString(2, sname);
int c = ps.executeUpdate();
if(c>0)
System.out.print("Succesfully Inserted");
else
System.out.print("Failed To Inserted");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Step5: Before executing this program, we need to add vender database specific jars to the
application and in our case, it is ojdbc14.jar
Right click on project Properties (click) and then you will get the below screen.
Click Add Jar/Folder button. Then you will get the below screen.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 18 of 155
Easy JavaWeb
Click Open button.Then you will get the below screen.
Click OK.
Step 6: Excecute “InsertRecord.java” by right click on it and then go to Run File and click it. Now we
can see the output of this program and we can observe it in second below firgire.
1.5. Getting Result
Here we will use ResultSet which Contains the selected records from the database. The
ResultSet contains the pointer which by default position at the first record.Here I am listing out
the some of important methods oftenly used.
String getString( int fieldno ) : Returns the value of the specified field. Field number
starts from 1.
String getString( String fieldname ) : Returns the value for the specified field name.
Similarly the other get methods are available for the remaining data types.
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 19 of 155
Easy JavaWeb
ResultSetMetaData getMetaData( ): Returns the ResultSetMetaData.
void close( ) :
Closes the result set.
JDBC has facilities to get information about a ResultSet or DB for a ResultSet, this information
may include the number and names of the columns, the types of the columns etc.For a DB this
information may include the name of the driver, the DB URL etc. This information about a
ResultSet or DB is known as metadata.
ResultSetMetaData: Contains the information of the result set and below are the some of
frequently used methods.
int getColumnCount( ): Returns the number of selected fields.
String getColumnName( int field no ) : Returns the label of the specified column.
DatabaseMetaData: Contains the information of database and we will get this object by calling
getMetaData() on connection object like below.
Connection con = DriverManager.getConnection( "jdbc:db2:TEST", "db2admin", "db2admin" );
DatabaseMetaData dmd = con.getMetaData( )
Example9:Retrieving the information from Product table in DB2 .
import java.sql.*;
class SelectProducts
{
public static void main(java.lang.String[ ] args)
{
try
{
Class.forName( "COM.ibm.db2.jdbc.app.DB2Driver" );
String url = "jdbc:db2://10.0.52.86:6789/Test";
Connection con = DriverManager.getConnection( url, "db2admin", " db2admin " );
Statement statement = con.createStatement( );
ResultSet rs = statement.executeQuery("SELECT NAME, PRICE FROM PRODUCT");
while ( rs.next( ) )
{
String name = rs.getString( "NAME" );
float price = rs.getFloat( "PRICE" );
System.out.println("Name: "+name+", price: "+price);
}
statement.close( );
con.close( );
}
catch( Exception e ) { e.printStackTrace( ); }
}
}
Example10:Displaying a table in Oracle in terms of table formate .
import java.sql.*;
public class select {
public static void main(String a[]) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
String url="jdbc:oracle:thin:@localhost:1521:orcl";
Connection con = DriverManager.getConnection(url, "scott", "tiger");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from mesmca");
ResultSetMetaData rsmd = rs.getMetaData();
int cols = rsmd.getColumnCount();
for (int i = 1; i <= cols; i++) {
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 20 of 155
Easy JavaWeb
System.out.print(rsmd.getColumnName(i) + "\t");
}
System.out.print("\n");
while (rs.next()) {
for (int i = 1; i <= cols; i++) {
System.out.print(rs.getString(i) + "\t");
}
System.out.print("\n");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Example11:Program to display a table information in JTable.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import java.sql.*;
import java.util.Vector;
public class JTableJDBC {
public static void main(String args[]) {
MyFrame f = new MyFrame();
f.setTitle("Query Frame");
f.setBounds(50, 50, 350, 200);
f.setVisible(true);
}
}
class MyFrame extends JFrame implements ActionListener {
JLabel l1;
JTextArea query;
JPanel p1;
JButton b1, b2;
Container c;
Connection con;
Statement stmt;
MyFrame() {
l1 = new JLabel("Enter Query: ");
query = new JTextArea();
p1 = new JPanel();
b1 = new JButton("Execute Query");
b2 = new JButton("Exit Program");
c = getContentPane();
c.add(l1, BorderLayout.NORTH);
c.add(query, BorderLayout.CENTER);
query.setFont(new Font("SanSerif", Font.BOLD, 14));
c.add(p1, BorderLayout.SOUTH);
p1.setLayout(new FlowLayout());
p1.add(b1);
p1.add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
openConnection();
}
void openConnection() {
try {
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 21 of 155
Easy JavaWeb
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL", "scott",
"tiger");
stmt = con.createStatement();
System.out.println("Ok");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex);
}
}
void closeConnection() {
try {
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
System.out.println("Connection closed....");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Error: " + ex);
}
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == b1) {
showData();
} else if (e.getSource() == b2) {
closeConnection();
System.exit(0);
}
}
void showData() {
try {
String str = query.getText().trim();
ResultSet rs = stmt.executeQuery(str);
ResultSetMetaData rsmd = rs.getMetaData();
int i, n;
n = rsmd.getColumnCount();
Vector heads = new Vector();
Vector rowData = new Vector();
// Getting Headings into the 1st vector
for (i = 1; i <= n; i++) {
heads.add(rsmd.getColumnLabel(i));
}
// Getting Data into the rowData
while (rs.next()) {
Vector curRow = new Vector();
for (i = 1; i <= n; i++) {
curRow.add(rs.getString(i));
}
// Add the current row to the row data
rowData.add(curRow);
}
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 22 of 155
Easy JavaWeb
DisplayFrame f = new DisplayFrame(rowData, heads);
f.setBounds(50, 50, 600, 300);
f.setTitle(str);
f.setVisible(true);
rs.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Cannot execute query");
}
}
}
class DisplayFrame extends JFrame {
JScrollPane jsp;
JTable table;
Container c;
int vsp = JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED;
int hsp = JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED;
DisplayFrame(Vector rowData, Vector heads) {
c = getContentPane();
table = new JTable(rowData, heads);
table.setFont(new Font("SanSerif", Font.BOLD, 14));
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
jsp = new JScrollPane(table, vsp, hsp);
c.add(jsp);
}
}
1.6. Calling Procedures & Functions
A stored procedure/function is a program that is resides and executed within a database server.
We can call the procedure/function from a Java class using a special syntax. When you call it,
the name of the procedure/function and the parameters you specify are sent over the JDBC
connection to the DBMS, which executes the procedure/function and returns the results (if any)
back over the connection.
As stored procedures run in the DBMS itself, they can help to reduce latency in applications.
Rather than executing four or five SQL statements in your Java code, we can just execute one
stored procedure/function that does the operations for us on the database server side. Reducing
the number of network trips will improve application performance.
JDBC supports calling stored procedures with the CallableStatement class which is a subclass of
PreparedStatement.Below are the syntaxes of calling procedures and functions respectively.
{call <procedure-name>[<arg1>,<arg2>, ...]}
{?= call <function-name>[<arg1>,<arg2>, ...]}
Example12:Calling a PL/SQL procedure of oracle from java.
import java.sql.*;
public class CallProcedure
create or replace procedure mesmcaProc(a number,b varchar2)
{
is
public static void main(String[] param)
begin
{
insert into mesmca values(a,b);
String sname = "Satya";
end;
int sno = 44;
/
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL",
"scott", "tiger");
CallableStatement st =con.prepareCall("{call mesmcaProc(?,?)}");
st.setInt(1, sno);
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 23 of 155
Easy JavaWeb
st.setString(2, sname);
st.execute();
}
catch (Exception localException)
{
}
}
}
Example13:Calling a PL/SQL function of oracle from java.
Create or Replace Function getnetamt(qty in Number,rate in Number)
return Number
is
tamt number(12,2);
tdisc number(12,2);
tnet number(12,2);
Begin
tamt:= qty * rate;
if tamt >= 5000 then
tdisc:=(tamt * 10)/100;
else
tdisc:=(tamt * 5)/100;
end if;
tnet:= tamt - tdisc;
return tnet
end;
import java.io.*;
import java.sql.*;
class calstmt
{
public static void main(String args[])
{
try
{
BufferedReader stdin = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Getting Connection...");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con =
DriverManager.getConnection( "jdbc:odbc:javaoracle", "scott", "tiger");
double rate,net;
while(true)
{
try
{
System.out.println( );
CallableStatement cs = con.prepareCall("{? = call getnetamt(?,?)}");
cs.registerOutParameter(1,Types.DOUBLE);
System.out.println("Enter Qty purchased: ");
int qty = Integer.parseInt(stdin.readLine());
System.out.println("Enter Rate per unit: ");
rate = Double.parseDouble(stdin.readLine());
cs.setInt(2,qty);
cs.setDouble(3,rate);
cs.execute(); // call the oracle function getnetamt
net = cs.getDouble(1);
// 1st parameter
System.out.println("----------------------------------------");
System.out.println("Net Amount: "+net);
cs.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
System.out.print("Any more Data [y/n]: ");
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 24 of 155
Easy JavaWeb
String str = stdin.readLine().toUpperCase().trim();
if(str.startsWith("N"))
break;
}
con.close();
System.out.println("Connection closed....");
}
catch(Exception ex)
{
System.out.println("Error: "+ex);
}
}
}
1.7. Scrollable & Updatable ResultSets
These features are may not be supported by all DBMSs as it is not a mandatory requirement for
JDBC 2.0 compatibility.
Whenever we open the resultset using the executingQuery( ) function the result set will be
opened in a forward only mode. i.e., the record pointer can be moved only in the forward
direction but not in the backward direction.In order to open in a scrollable mode the statement
should be created with the following parameters.
Syntax: Statement
SQLException
createStatement(
int
ResultSetType,
int
concurrencyType
)
throws
ResultSetType :
ResultSet.TYPE_FORWARD_ONLY: The record pointer can be moved only in the forward
direction( default ) means not scrollable. Does not reflect changes made to the underlying data.
ResultSet.TYPE_SCROLL_INSENSITIVE: The record pointer is scrollable, but the ResultSet
doesn’t effects for the new changes made by the other applications means it does not reflect
changes made to the underlying data.
ResultSet.TYPE_SCROLL_SENSITIVE: The record pointer is scrollable, and also effects the
ResultSet also effects the client applications means reflects changes made to the underlying
data.
Moving the Cursor to a Designated Row : You can move the cursor to a particular row in a
ResultSet object. The methods first, last, beforeFirst, and afterLast move the cursor to the
position their names indicate. The method absolute will move the cursor to the row number
indicated in the argument passed to it. If the number is positive, the cursor moves the given
number from the beginning, so calling absolute(1) puts the cursor on the first row. If the
number is negative, the cursor moves the given number from the end, so calling absolute(-1)
puts the cursor on the last row.
boolean next( ): Moves the record pointer to the next record returns true on success and false
on failure.
boolean previous( ): Moves the record pointer to the prev record returns true on success and
false on failure.
boolean first( ): Moves the record pointer to the first record returns true on success and false
on failure.
boolean last( ): Moves the record pointer to the last record returns true on success and false on
failure.
Call Me@9000387222 for any further assistance..
Sivaramayya@9000387222/9866723206
www. javasiva.in
Page 25 of 155
Download