Sunteți pe pagina 1din 20

Home

Interview experience

Java Interview Questions

Java Projects

Downloads

Contact us

Java2Natar az
JAVA FRAMEWORK SOFTWARE ADVANCED JAVA CORE JAVA EXAMPLE PROGRAMS BY NATARAZ SIR NOTES BY NATARAJ SIR VOICE RECORDING

Showing posts with label advanced java. Show all posts


Sunday, 6 January 2013

TOP 8 JAVA PEOPLE

Followers

Advanced java

About Me Blog Archive


2013 (40) August (10) March (11) January (19) Example programs by nataraz sir JDBC,SERVLET,JS PJAVA...view and download SPRING ... Java framework software Advanced java Voice Recording, soon here available on nataraj sir class notes : Spring Spring is the most popular application development... Spring is the most popular application development... Spring is the most popular application development... Posted by mahesh posa Labels: advanced java
M A H E S H
Follow

P O

13

V I E W M Y P R O F I L E

C O M

Saturday, 5 January 2013

JSP

What is JavaServer Pages?


JavaServer Pages (JSP) is a technology for developing web pages that support dynamic content which helps developers insert java code in HTML pages by making use of special JSP tags, most of which start with <% and end with %>. A JavaServer Pages component is a type of Java servlet that is designed to fulfill the role of a user interface for a Java web application. Web developers write JSPs as text files that combine HTML or XHTML code, XML elements, and embedded JSP actions and commands. Using JSP, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically. JSP tags can be used for a variety of purposes, such as retrieving information from a database or registering user preferences, accessing JavaBeans components, passing control between pages and sharing information between requests, pages etc.

Why Use JSP?


JavaServer Pages often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But JSP offer several advantages in comparison with the CGI.

converted by Web2PDFConvert.com

Hibernate Struts 2.X Struts 1.X Struts JSP SERVLETS JDBC CORE JAVA

Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself instead of having a separate CGI files. JSP are always compiled before it's processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested. JavaServer Pages are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc. JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines. Finally, JSP is an integral part of J2EE, a complete platform for enterprise class applications. This means that JSP can play a part in the simplest applications to the most complex and demanding.

Setting up JSP Environment


This step involves downloading an implementation of the Java Software Development Kit (SDK) and setting up PATH environment variable appropriately. You can downloaded SDK from Oracle's Java site: Java SE Downloads. Once you download your Java implementation, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and installed the SDK in C:\jdk1.5.0_20, you would put the following line in your C:\autoexec.bat file.
set PATH=C:\jdk1.5.0_20\bin;%PATH% set JAVA_HOME=C:\jdk1.5.0_20

Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you would put the following into your .cshrc file.
setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH setenv JAVA_HOME /usr/local/jdk1.5.0_20

Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java.

Setting up Web Server: Tomcat


A number of Web Servers that support JavaServer Pages and Servlets development are available in the market. Some web servers are freely downloadable and Tomcat is one of them. Apache Tomcat is an open source software implementation of the JavaServer Pages and Servlet technologies and can act as a standalone server for testing JSP and Servlets and can be integrated with the Apache Web Server. Here are the steps to setup Tomcat on your machine: Download latest version of Tomcat from http://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations. Tomcat can be started by executing the following commands on windows machine:
%CATALINA_HOME%\bin\startup.bat or C:\apache-tomcat-5.5.29\bin\startup.bat
converted by Web2PDFConvert.com

Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine:
$CATALINA_HOME/bin/startup.sh or /usr/local/apache-tomcat-5.5.29/bin/startup.sh

After a successful startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine then it should display following result:

Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site: http://tomcat.apache.org

JSP Processing:
The following steps explain how the web server creates the web page using JSP: As with a normal page, your browser sends an HTTP request to the web server. The web server recognizes that the HTTP request is for a JSP page and forwards it to a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead of .html. The JSP engine loads the JSP page from disk and converts it into a servlet content. This conversion is very simple in which all template text is converted to println( ) statements and all JSP elements are converted to Java code that implements the corresponding dynamic behavior of the page. The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet engine. A part of the web server called the servlet engine loads the Servlet class and executes it. During execution, the servlet produces an output in HTML format, which the servlet engine passes to the web server inside an HTTP response. The web server forwards the HTTP response to your browser in terms of static HTML content. Finally web browser handles the dynamically generated HTML page inside the HTTP response exactly as if it were a static page. All the above mentioned steps can be shown below in the following diagram:

converted by Web2PDFConvert.com

The Scriptlet:
A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language. Following is the syntax of Scriptlet:
<% code fragment %>

You can write XML equivalent of the above syntax as follows:


<jsp:scriptlet> code fragment </jsp:scriptlet>

Any text, HTML tags, or JSP elements you write must be outside the scriptlet. Following is the simple and first example for JSP:
<html> <head><title>Hello World</title></head> <body> Hello World!<br/> <% out.println("Your IP address is " + request.getRemoteAddr()); %> </body> </html>

NOTE: Assuming that Apache Tomcat is installed in C:\apache-tomcat-7.0.2 and your environment is setup as per environment setup tutorial. Let us keep above code in JSP file hello.jsp and put this file in C:\apache-tomcat7.0.2\webapps\ROOT directory and try to browse it by giving URL http://localhost:8080/hello.jsp. This would generate following result:

JSP Declarations:
A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file. Following is the syntax of JSP Declarations:
<%! declaration; [ declaration; ]+ ... %>

You can write XML equivalent of the above syntax as follows:

converted by Web2PDFConvert.com

<jsp:declaration> code fragment </jsp:declaration>

Following is the simple example for JSP Comments:


<%! int i = 0; %> <%! int a, b, c; %> <%! Circle a = new Circle(2.0); %>

JSP Expression:
A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file. Because the value of an expression is converted to a String, you can use an expression within a line of text, whether or not it is tagged with HTML, in a JSP file. The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression. Following is the syntax of JSP Expression:
<%= expression %>

You can write XML equivalent of the above syntax as follows:


<jsp:expression> expression </jsp:expression>

Following is the simple example for JSP Expression:


<html> <head><title>A Comment Test</title></head> <body> <p> Today's date: <%= (new java.util.Date()).toLocaleString()%> </p> </body> </html>

This would generate following result: Today's date: 11-Sep-2010 21:24:25

JSP Comments:
JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out" part of your JSP page. Following is the syntax of JSP comments:
<%-- This is JSP comment --%>

Following is the simple example for JSP Comments:


<html> <head><title>A Comment Test</title></head> <body> <h2>A Test of Comments</h2> <%-- This comment will not be visible in the page source --%> </body> </html>

This would generate following result:

A Test of Comments
There are a small number of special constructs you can use in various cases to insert

converted by Web2PDFConvert.com

comments or characters that would otherwise be treated specially. Here's a summary: Syntax <%-- comment --%> <!-- comment --> <\% %\> \' \" Purpose A JSP comment. Ignored by the JSP engine. An HTML comment. Ignored by the browser. Represents static <% literal. Represents static %> literal. A single quote in an attribute that uses single quotes. A double quote in an attribute that uses double quotes.

JSP Directives:
A JSP directive affects the overall structure of the servlet class. It usually has the following form:
<%@ directive attribute="value" %>

There are three types of directive tag: Directive <%@ page ... %> <%@ include ... %> <%@ taglib ... %> Description Defines page-dependent attributes, such as scripting language, error page, and buffering requirements. Includes a file during the translation phase. Declares a tag library, containing custom actions, used in the page

We would explain JSP directive in separate chapter JSP - Directives

JSP Actions:
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin. There is only one syntax for the Action element, as it conforms to the XML standard:
<jsp:action_name attribute="value" />

Action elements are basically predefined functions and there are following JSP actions available: Syntax jsp:include jsp:include jsp:useBean jsp:setProperty jsp:getProperty jsp:forward jsp:plugin jsp:element jsp:attribute jsp:body jsp:text Purpose Includes a file at the time the page is requested Includes a file at the time the page is requested Finds or instantiates a JavaBean Sets the property of a JavaBean Inserts the property of a JavaBean into the output Forwards the requester to a new page Generates browser-specific code that makes an OBJECT or EMBED tag for the Java plugin Defines XML elements dynamically. Defines dynamically defined XML element's attribute. Defines dynamically defined XML element's body. Use to write template text in JSP pages and documents.

We would explain JSP actions in separate chapter JSP - Actions

converted by Web2PDFConvert.com

JSP Implicit Objects:


JSP supports nine automatically defined variables, which are also called implicit objects. These variables are: Objects request Description This is the HttpServletRequest object associated with the request. This is the HttpServletResponse object associated with the response to the client. This is the PrintWriter object used to send output to the client. This is the HttpSession object associated with the request. This is the ServletContext object associated with application context. This is the ServletConfig object associated with the page. This encapsulates use of server-specific features like higher performance JspWriters. This is simply a synonym for this, and is used to call the methods defined by the translated servlet class. The Exception object allows the exception data to be accessed by designated JSP.

response

out

session

application

config

pageContext

page

Exception

We would explain JSP Implicit Objects in separate chapter JSP - Implicit Objects.

Control-Flow Statements:
JSP provides full power of Java to be embeded in your web application. You can use all the APIs and building blocks of Java in your JSP programming including decision making statements, loops etc.

Decision-Making Statements:
The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each line with HTML text included between Scriptlet tags.
<%! int day = 3; %> <html> <head><title>IF...ELSE Example</title></head> <body> <% if (day == 1 | day == 7) { %> <p> Today is weekend</p> <% } else { %> <p> Today is not weekend</p> <% } %> </body> </html>

This would produce following result: Today is not weekend Now look at the following switch...case block which has been written a bit differentlty using out.println() and inside Scriptletas:
<%! int day = 3; %> <html> <head><title>SWITCH...CASE Example</title></head> <body> <%

converted by Web2PDFConvert.com

switch(day) { case 0: out.println("It\'s Sunday."); break; case 1: out.println("It\'s Monday."); break; case 2: out.println("It\'s Tuesday."); break; case 3: out.println("It\'s Wednesday."); break; case 4: out.println("It\'s Thursday."); break; case 5: out.println("It\'s Friday."); break; default: out.println("It's Saturday."); } %> </body> </html>

This would produce following result: It's Wednesday.

Loop Statements:
You can also use three basic types of looping blocks in Java: for, while,and do.while blocks in your JSP programming. Let us look at the following for loop example:
<%! int fontSize; %> <html> <head><title>FOR LOOP Example</title></head> <body> <%for ( fontSize = 1; fontSize <= 3; fontSize++){ %> <font color="green" size="<%= fontSize %>"> JSP Tutorial </font><br /> <%}%> </body> </html>

This would produce following result:


JSP Tutorial

JSP Tutorial

JSP Tutorial Above example can be written using while loop as follows:
<%! int fontSize; %> <html> <head><title>WHILE LOOP Example</title></head> <body> <%while ( fontSize <= 3){ %> <font color="green" size="<%= fontSize %>"> JSP Tutorial </font><br /> <%fontSize++;%> <%}%>
converted by Web2PDFConvert.com

</body> </html>

This would also produce following result:


JSP Tutorial

JSP Tutorial

JSP Tutorial

JSP Operators:
JSP supports all the logical and arithmatic operators supported by Java. Following table give a list of all the operators with the highest precedence appear at the top of the table, those with the lowest appear at the bottom. Within an expression, higher precedenace operators will be evaluated first. Category Postfix Unary Multiplicative Additive Shift Relational Equality Bitwise AND Bitwise XOR Bitwise OR Logical AND Logical OR Conditional Assignment Comma Operator () [] . (dot operator) ++ - - ! ~ */% +>> >>> << > >= < <= == != & ^ | && || ?: Associativity Left to right Right to left Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Left to right Right to left

= += -= *= /= %= >>= <<= &= ^= |= Right to left , Left to right

JSP Literals:
The JSP expression language defines the following literals: Boolean: true and false Integer: as in Java Floating point: as in Java String: with single and double quotes; " is escaped as \", ' is escaped as \', and \ is escaped as \\. Null: null Posted by mahesh posa Labels: advanced java

SERVLETS

What are Servlets?


Java Servlets are programs that run on a Web or Application server and act as a middle layer between a request coming from a Web browser or other HTTP client and

converted by Web2PDFConvert.com

databases or applications on the HTTP server. Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically. Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI. Performance is significantly better. Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request. Servlets are platform-independent because they are written in Java. Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted. The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already.

Servlets Architecture:
Following diagram shows the position of Servelts in a Web Application.

Servlets Packages:
Java Servlets are Java classes run by a web server that has an interpreter that supports the Java Servlet specification. Servlets can be created using the javax.servlet and javax.servlet.http packages, which are a standard part of the Java's enterprise edition, an expanded version of the Java class library that supports large-scale development projects. These classes implement the Java Servlet and JSP specifications. At the time of writing this tutorial, the versions are Java Servlet 2.5 and JSP 2.1. Java servlets have been created and compiled just like any other Java class. After you install the servlet packages and add them to your computer's Classpath, you can compile servlets with the JDK's Java compiler or any other current compiler.

Setting up Java Development Kit


This step involves downloading an implementation of the Java Software Development Kit (SDK) and setting up PATH environment variable appropriately. You can download SDK from Sun's Java servlet site: http://java.sun.com/products/servlet/. Once you download your Java implementation, follow the given instructions to install and configure the setup. Finally set PATH and JAVA_HOME environment variables to refer to the directory that contains java and javac, typically java_install_dir/bin and java_install_dir respectively. If you are running Windows and installed the SDK in C:\jdk1.5.0_20, you would put the following line in your C:\autoexec.bat file.
set PATH=C:\jdk1.5.0_20\bin;%PATH% set JAVA_HOME=C:\jdk1.5.0_20

Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the PATH value and press the OK button. On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the C shell, you would put the following into your .cshrc file.

converted by Web2PDFConvert.com

setenv PATH /usr/local/jdk1.5.0_20/bin:$PATH setenv JAVA_HOME /usr/local/jdk1.5.0_20

Alternatively, if you use an Integrated Development Environment (IDE) like Borland JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to confirm that the IDE knows where you installed Java.

Setting up Web Server: Tomcat


A number of Web Servers that support servlets are available in the market. Some web servers are freely downloadable and Tomcat is one of them. Apache Tomcat is an open source software implementation of the Java Servlet and JavaServer Pages technologies and can act as a standalone server for testing servlets and can be integrated with the Apache Web Server. Here are the steps to setup Tomcat on your machine: Download latest version of Tomcat from http://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenient location. For example in C:\apache-tomcat-5.5.29 on windows, or /usr/local/apache-tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variable pointing to these locations. Tomcat can be started by executing the following commands on windows machine:
$CATALINA_HOME\bin\startup.bat or C:\apache-tomcat-5.5.29\bin\startup.bat

Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.) machine:
$CATALINA_HOME/bin/startup.sh or /usr/local/apache-tomcat-5.5.29/bin/startup.sh

After startup, the default web applications included with Tomcat will be available by visiting http://localhost:8080/. If everything is fine then it should display following result:

Further information about configuring and running Tomcat can be found in the documentation included here, as well as on the Tomcat web site: http://tomcat.apache.org Tomcat can be stopped by executing the following commands on windows machine:

converted by Web2PDFConvert.com

C:\apache-tomcat-5.5.29\bin\shutdown

Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.) machine:
/usr/local/apache-tomcat-5.5.29/bin/shutdown.sh

Setting up CLASSPATH
Since servlets are not part of the Java Platform, Standard Edition, you must identify the servlet classes to the compiler. If you are running Windows, you need to put the following lines in your C:\autoexec.bat file.
set CATALINA=C:\apache-tomcat-5.5.29 set CLASSPATH=%CATALINA%\common\lib\servlet-api.jar;%CLASSPATH%

Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, select Properties, then Advanced, then Environment Variables. Then, you would update the CLASSPATH value and press the OK button. On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines into your .cshrc file.
setenv CATALINA=/usr/local/apache-tomcat-5.5.29 setenv CLASSPATH $CATALINA/common/lib/servlet-api.jar:$CLASSPATH

NOTE: Assuming that your development directory is C:\ServletDevel (Windows) or /usr/ServletDevel (Unix) then you would need to add these directories as well in CLASSPATH in similar way as you have added above.

Sample Code for Hello World:


Following is the sample source code structure of a servlet example to write Hello World:
// Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloWorld extends HttpServlet { private String message; public void init() throws ServletException { // Do required initialization message = "Hello World"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); // Actual logic goes here. PrintWriter out = response.getWriter(); out.println("<h1>" + message + "</h1>"); } public void destroy()

converted by Web2PDFConvert.com

{ // do nothing. } }

Compiling a Servlet:
Let us put above code if HelloWorld.java file and put this file in C:\ServletDevel (Windows) or /usr/ServletDevel (Unix) then you would need to add these directories as well in CLASSPATH. Assuming your environment is setup properly, go in ServletDevel directory and compile HelloWorld.java as follows:
$ javac HelloWorld.java

If the servlet depends on any other libraries, you have to include those JAR files on your CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not using any other library in Hello World program. This command line uses the built-in javac compiler that comes with the Sun Microsystems Java Software Development Kit (JDK). For this command to work properly, you have to include the location of the Java SDK that you are using in the PATH environment variable. If everything goes fine, above compilation would produce HelloWorld.class file in the same directory. Next section would explain how a compiled servlet would be deployed in production.

Servlet Deployment:
By default, a servlet application is located at the path <Tomcat-installationdirectory>/webapps/ROOT and the class file would reside in <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes. If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class must be located in WEB-INF/classes/com/myorg/MyServlet.class. For now, let us copy HelloWorld.class into <Tomcat-installationdirectory>/webapps/ROOT/WEB-INF/classes and create following entries in web.xml file located in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/
<servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/HelloWorld</url-pattern> </servlet-mapping>

Above entries to be created inside <web-app>...</web-app> tags available in web.xml file. There could be various entries in this table already available, but never mind. You are almost done, now let us start tomcat server using <Tomcat-installationdirectory>\bin\startup.bat (on windows) or <Tomcat-installationdirectory>/bin/startup.sh (on Linux/Solaris etc.) and finally type http://localhost:8080/HelloWorld in browser's address box. If everything goes fine, you would get following result:

converted by Web2PDFConvert.com

To go in detail of servlet, you can go through complete tutorial starting from start : Java Servlet Posted by mahesh posa Labels: advanced java

JDBC

What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases. The JDBC library includes APIs for each of the tasks commonly associated with database usage: Making a connection to a database Creating SQL or MySQL statements Executing that SQL or MySQL queries in the database Viewing & Modifying the resulting records

Pre-Requisite:
You need to have good understanding on the following two subjects to learn JDBC: 1. Core JAVA Programming 2. SQL or MySQL Database

JDBC - Environment Setup:


Make sure you have done following setup: 1. Core JAVA Installation 2. SQL or MySQL Database Installation Apart from the above you need to setup a database which you would use for your project. Assuming this is EMP and you have created on table Employees within the same database.

Creating JDBC Application:


There are six steps involved in building a JDBC application which I'm going to brief in this tutorial:

Import the packages:


This requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice as follows:
//STEP 1. Import required packages import java.sql.*;

converted by Web2PDFConvert.com

Register the JDBC driver:


This requires that you initialize a driver so you can open a communications channel with the database. Following is the code snippet to achieve this:
//STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver");

Open a connection:
This requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with the database as follows:
//STEP 3: Open a connection // Database credentials static final String USER = "username"; static final String PASS = "password"; System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS);

Execute a query:
This requires using an object of type Statement or PreparedStatement for building and submitting an SQL statement to the database as follows:
//STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT id, first, last, age FROM Employees"; ResultSet rs = stmt.executeQuery(sql);

If there is an SQL UPDATE,INSERT or DELETE statement required, then following code snippet would be required:
//STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "DELETE FROM Employees"; ResultSet rs = stmt.executeUpdate(sql);

Extract data from result set:


This step is required in case you are fetching data from the database. You can use the appropriate ResultSet.getXXX() method to retrieve the data from the result set as follows:
//STEP 5: Extract data from result set while(rs.next()){ //Retrieve by column name int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last"); //Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); }

Clean up the environment:


converted by Web2PDFConvert.com

You should explicitly close all database resources versus relying on the JVM's garbage collection as follows:
//STEP 6: Clean-up environment rs.close(); stmt.close(); conn.close();

First JDBC Program:


Based on the above steps, we can have following consolidated sample code which we can use as a template while writing our JDBC code: This sample code has been written based on the environment and database setup done in Environment chapter.
//STEP 1. Import required packages import java.sql.*; public class FirstExample { // JDBC driver name and database URL static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; static final String DB_URL = "jdbc:mysql://localhost/EMP"; // Database credentials static final String USER = "username"; static final String PASS = "password"; public static void main(String[] args) { Connection conn = null; Statement stmt = null; try{ //STEP 2: Register JDBC driver Class.forName("com.mysql.jdbc.Driver"); //STEP 3: Open a connection System.out.println("Connecting to database..."); conn = DriverManager.getConnection(DB_URL,USER,PASS); //STEP 4: Execute a query System.out.println("Creating statement..."); stmt = conn.createStatement(); String sql; sql = "SELECT id, first, last, age FROM Employees"; ResultSet rs = stmt.executeQuery(sql); //STEP 5: Extract data from result set while(rs.next()){ //Retrieve by column name int id = rs.getInt("id"); int age = rs.getInt("age"); String first = rs.getString("first"); String last = rs.getString("last"); //Display values System.out.print("ID: " + id); System.out.print(", Age: " + age); System.out.print(", First: " + first); System.out.println(", Last: " + last); } //STEP 6: Clean-up environment rs.close(); stmt.close(); conn.close();

converted by Web2PDFConvert.com

}catch(SQLException se){ //Handle errors for JDBC se.printStackTrace(); }catch(Exception e){ //Handle errors for Class.forName e.printStackTrace(); }finally{ //finally block used to close resources try{ if(stmt!=null) stmt.close(); }catch(SQLException se2){ }// nothing we can do try{ if(conn!=null) conn.close(); }catch(SQLException se){ se.printStackTrace(); }//end finally try }//end try System.out.println("Goodbye!"); }//end main }//end FirstExample

Now let us compile above example as follows:


C:\>javac FirstExample.java C:\>

When you run FirstExample , it produces following result:


C:\>java FirstExample Connecting to database... Creating statement... ID: 100, Age: 18, First: Zara, Last: Ali ID: 101, Age: 25, First: Mahnaz, Last: Fatma ID: 102, Age: 30, First: Zaid, Last: Khan ID: 103, Age: 28, First: Sumit, Last: Mittal C:\>

SQLException Methods:
A SQLException can occur both in the driver and the database. When such an exception occurs, an object of type SQLException will be passed to the catch clause. The passed SQLException object has the following methods available for retrieving additional information about the exception: Method getErrorCode( ) Description Gets the error number associated with the exception. Gets the JDBC driver's error message for an error handled by the driver or gets the Oracle error number and message for a database error. Gets the XOPEN SQLstate string. For a JDBC driver error, no useful information is returned from this method. For a database error, the five-digit XOPEN SQLstate code is returned. This method can return null. Gets the next Exception object in the exception chain.

getMessage( )

getSQLState( )

getNextException( )

converted by Web2PDFConvert.com

printStackTrace( )

Prints the current exception, or throwable, and its backtrace to a standard error stream. Prints this throwable and its backtrace to the print stream you specify. Prints this throwable and its backtrace to the print writer you specify.

printStackTrace(PrintStream s)

printStackTrace(PrintWriter w)

By utilizing the information available from the Exception object, you can catch an exception and continue your program appropriately. Here is the general form of a try block:
try { // Your risky code goes between these curly braces!!! } catch(Exception ex) { // Your exception handling code goes between these // curly braces, similar to the exception clause // in a PL/SQL block. } finally { // Your must-always-be-executed code goes between these // curly braces. Like closing database connection. }

JDBC - Data Types:


The following table summarizes the default JDBC data type that the Java data type is converted to when you call the setXXX() method of the PreparedStatement or CallableStatement object or the ResultSet.updateXXX() method. SQL VARCHAR CHAR LONGVARCHAR BIT NUMERIC TINYINT SMALLINT INTEGER BIGINT REAL FLOAT DOUBLE VARBINARY BINARY DATE TIME TIMESTAMP CLOB BLOB ARRAY REF JDBC/Java java.lang.String java.lang.String java.lang.String boolean java.math.BigDecimal byte short int long float float double byte[ ] byte[ ] java.sql.Date java.sql.Time java.sql.Timestamp java.sql.Clob java.sql.Blob java.sql.Array java.sql.Ref setXXX setString setString setString setBoolean setBigDecimal setByte setShort setInt setLong setFloat setFloat setDouble setBytes setBytes setDate setTime setTimestamp setClob setBlob setARRAY SetRef updateXXX updateString updateString updateString updateBoolean updateBigDecimal updateByte updateShort updateInt updateLong updateFloat updateFloat updateDouble updateBytes updateBytes updateDate updateTime updateTimestamp updateClob updateBlob updateARRAY updateRef
converted by Web2PDFConvert.com

STRUCT

java.sql.Struct

SetStruct

updateStruct

JDBC 3.0 has enhanced support for BLOB, CLOB, ARRAY, and REF data types. The ResultSet object now has updateBLOB(), updateCLOB(), updateArray(), and updateRef() methods that enable you to directly manipulate the respective data on the server. The setXXX() and updateXXX() methods enable you to convert specific Java types to specific JDBC data types. The methods, setObject() and updateObject(), enable you to map almost any Java type to a JDBC data type. ResultSet object provides corresponding getXXX() method for each data type to retrieve column value. Each method can be used with column name or by its ordinal position. SQL VARCHAR CHAR LONGVARCHAR BIT NUMERIC TINYINT SMALLINT INTEGER BIGINT REAL FLOAT DOUBLE VARBINARY BINARY DATE TIME TIMESTAMP CLOB BLOB ARRAY REF STRUCT JDBC/Java java.lang.String java.lang.String java.lang.String boolean java.math.BigDecimal byte short int long float float double byte[ ] byte[ ] java.sql.Date java.sql.Time java.sql.Timestamp java.sql.Clob java.sql.Blob java.sql.Array java.sql.Ref java.sql.Struct setXXX setString setString setString setBoolean setBigDecimal setByte setShort setInt setLong setFloat setFloat setDouble setBytes setBytes setDate setTime setTimestamp setClob setBlob setARRAY SetRef SetStruct getXXX getString getString getString getBoolean getBigDecimal getByte getShort getInt getLong getFloat getFloat getDouble getBytes getBytes getDate getTime getTimestamp getClob getBlob getARRAY getRef getStruct

JDBC - Batch Processing:


Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance. JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature. The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together.

converted by Web2PDFConvert.com

The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement. Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove.

JDBC - Streaming Data:


A PreparedStatement object has the ability to use input and output streams to supply parameter data. This enables you to place entire files into database columns that can hold large values, such as CLOB and BLOB data types. There are following methods which can be used to stream data: 1. setAsciiStream(): This method is used to supply large ASCII values. 2. setCharacterStream(): This method is used to supply large UNICODE values. 3. setBinaryStream(): This method is used to supply large binary values. The setXXXStream() method requires an extra parameter, the file size, besides the parameter placeholder. This parameter informs the driver how much data should be sent to the database using the stream. For a detail on all these concept, you need to go through the complete tutorial. Posted by mahesh posa Labels: advanced java

Home Business Cards Architectures Stock Market Auto insurance quote comparison Marketing

Older Posts

Advantages of credit cards

Copyright (c) 2012 Java 2 Nataraz | powered by Signa software solutions

converted by Web2PDFConvert.com

S-ar putea să vă placă și