JSP and JDBC Questions
- What is the query used to display all tables names in SQL Server (Query analyzer)?select * from information_schema.tables
- How many types of JDBC Drivers are present and what are they?There are 4 types of JDBC Drivers
- JDBC-ODBC Bridge Driver
- Native API Partly Java Driver
- Network protocol Driver
- JDBC Net pure Java Driver
- Can we implement an interface in a JSP?No
- What is the difference between ServletContext and PageContext?ServletContext: Gives the information about the container. PageContext: Gives the information about the Request
- What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?request.getRequestDispatcher(path): In order to create it we need to give the relative path of the resource, context.getRequestDispatcher(path): In order to create it we need to give the absolute path of the resource.
- How to pass information from JSP to included JSP?Using <%jsp:param> tag.
- What is the difference between directive include and jsp include?<%@ include>: Used to include static resources during translation time. JSP include: Used to include dynamic content or static content during runtime.
- What is the difference between RequestDispatcher and sendRedirect?RequestDispatcher: server-side redirect with request and response objects. sendRedirect : Client-side redirect with new request and response objects.
- How does JSP handle runtime exceptions?Using errorPage attribute of page directive and also we need to specify isErrorPage=true if the current page is intended to URL redirecting of a JSP.
- How do you delete a Cookie within a JSP?Cookie mycook = new Cookie("name","value");
- response.addCookie(mycook);
- Cookie killmycook = new Cookie("mycook","value");
- killmycook.setMaxAge(0);
- killmycook.setPath("/");
- killmycook.addCookie(killmycook);
- How do I mix JSP and SSI #include?If you’re just including raw HTML, use the #include directive as usual inside your .jsp file.<!--#include file="data.inc"---
- I made my class Cloneable but I still get Can’t access protected method clone. Why?Some of the Java books imply that all you have to do in order to have your class support clone() is implement the Cloneable interface. Not so. Perhaps that was the intent at some point, but that’s not the way it works currently. As it stands, you have to implement your own public clone() method, even if it doesn’t do anything special and just calls super.clone().
- Why is XML such an important development?It removes two constraints which were holding back Web developments: dependence on a single, inflexible document type (HTML) which was being much abused for tasks it was never designed for; the complexity of full SGML, whose syntax allows many powerful but hard-to-program options. XML allows the flexible development of user-defined document types. It provides a robust, non-proprietary, persistent, and verifiable file format for the storage and transmission of text and data both on and off the Web; and it removes the more complex options of SGML, making it easier to program for.
- What is the fastest type of JDBC driver?JDBC driver performance will depend on a number of issues:
- the quality of the driver code,
- the size of the driver code,
- the database server and its load,
- network topology,
- the number of times your request is translated to a different API.
In
general, all things being equal, you can assume that the more your
request and response change hands, the slower it will be. This means
that Type 1 and Type 3 drivers will be slower than Type 2 drivers
(the database calls are make at least three translations versus two),
and Type 4 drivers are the fastest (only one translation).
- How can I send user authentication information while makingURLConnection?You’ll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.
J2EE EJB Questions
- What is the relationship between local interfaces and container-managed relationships? - Entity beans that have container-managed relationships with other entity beans, must be accessed in the same local scope as those related beans, and therefore typically provide a local client view. In order to be the target of a container-managed relationship, an entity bean with container-managed persistence must provide a local interface.
- What does a remove method do for different cases of beans? - Stateless Session : Does not do anything to the bean as moving the bean from free pool to cache are managed by the container depending on load. Stateful Session: Removes the bean from the cache. Entity Bean: Deletes the bean (data) from persistent storage
- How does a container-managed relationship work? - An entity bean accesses related entity beans by means of the accessor methods for its container-managed relationship fields, which are specified by the cmr-field elements of its abstract persistence schema defined in the deployment descriptor. Entity bean relationships are defined in terms of the local interfaces of the related beans, and the view an entity bean presents to its related beans is defined by its local home and local interfaces. Thus, an entity bean can be the target of a relationship from another entity bean only if it has a local interface.
- What is the new basic requirement for a CMP entity bean class in 2.0 from that of ejb 1.1? - It must be abstract class. The container extends it and implements methods which are required for managing the relationships
- What are the basic classes required in the client for invoking an EJB? - The home and the remote interfaces, the implementation of the Naming Context Factory, the stubs and skeletons. In some App servers the stubs and the skeletons can be dynamically downloaded from the server
- What is the difference between Message Driven Beans and Stateless Session beans? - In several ways, the dynamic creation and allocation of message-driven bean instances mimics the behavior of stateless session EJB instances, which exist only for the duration of a particular method call. However, message-driven beans are different from stateless session EJBs (and other types of EJBs) in several significant ways:
- Message-driven beans process multiple JMS messages asynchronously, rather than processing a serialized sequence of method calls.
- Message-driven beans have no home or remote interface, and therefore cannot be directly accessed by internal or external clients. Clients interact with message-driven beans only indirectly, by sending a message to a JMS Queue or Topic.
- Only the container directly interacts with a message-driven bean by creating bean instances and passing JMS messages to those instances as necessary.
- The Container maintains the entire lifecycle of a message-driven bean; instances cannot be created or removed as a result of client requests or other API calls.
- What is the need for Clustering? - To scale the application so that it is highly available and has high throughput.
- What are the benefits of Clustering and workload management? - They are
- It balances client processing requests, allowing incoming work requests to be distributed according to a configured Workload Management selection policy.
- It provides fail over capability by redirecting client requests to a running server when one or more servers are unavailable. This improves the availability of applications and administrative services.
- It enables systems to be scaled up to serve a higher client load than provided by the basic configuration. With server groups and clones additional instances of servers can easily be added to the configuration.
- It enables servers to be transparently maintained and upgraded while applications remain available for users.
- It centralizes administration of application servers and other objects.
- What are the types of Scaling? - There are two types of scaling: Vertical Scaling and Horizontal Scaling.
- What is Vertical Scaling? - When multiple server clones of an application server are defined on the same physical m/c, it is called Vertical Scaling. The objective is to use the processing power of that m/c more efficiently.
- What is Horizontal Scaling? - When Clones of an application server are defined on multiple physical m/c, it is called Horizontal Scaling. The objective is to use more than one less powerful m/c more efficiently.
- What is a Server Group? - A server group is a template of an Application Server(and its contents) i.e, it is a logical representation of the application server. It has the same structure and attributes as the real Application Server, but it is not associated with any node, and does not correspond to any real server process running on any node.
- What is a Clone? - The copies of a server group are called Clones. But unlike a Server Group Clones are associated with a node and are real server process running in that node.
- What is Ripple Effect? - The process of propagating the changes in the properties of a server group during runtime to all the associated clones is called Ripple Effect.
- What level of Load Balancing is possible with EJBs? - The workload management service provides load balancing for the following types of enterprise beans: Homes of entity or session beans, Instances of entity beans, Instances of stateless session beans.
- What is the basic requirement for in-memory replication in Weblogic? - The data in session should consist only of Serialized objects. Only setAttribute function should be used to set objects in session.
- How JDBC services can be used in clustered environment? - Identical DataSource has to be created in each clustered server instances and configure to use different connection pools.
- What are the services that should not be used in a Clustered Environment? - Non-clustered services:
- File Services
- Time services
- Weblogic events
- Weblogic Workspaces (In WebLogic 5.1)
- Mention some tools to cluster Web Servers? - Web Servers can be clustered using Edge Server or DNS.
- What is in-memory replication? - The process by which the contents in the memory of one physical m/c are replicated in all the m/c in the cluster is called in-memory replication.
- Difference Between Abstraction and Encapsulation - Abstraction is removing some distinctions between objects, so as to show their commonalities. Encapsulation is hiding the details of the implementation of an object so that there are no external dependencies on the particular implementation.
JMS Interview Questions
- What are the types of messaging? - There are two kinds of Messaging. Synchronous messaging involves a client that waits for the server to respond to a message. Asynchronous messaging involves a client that does not wait for a message from the server. An event is used to trigger a message from a server.
- What is publish/subscribe messaging? - With publish/subscribe message passing the sending application/client establishes a named topic in the JMS broker/server and publishes messages to this queue. The receiving clients register (specifically, subscribe) via the broker to messages by topic; every subscriber to a topic receives each message published to that topic. There is a one-to-many relationship between the publishing client and the subscribing clients.
- Why doesn’t the JMS API provide end-to-end synchronous message delivery and notification of delivery? -Some messaging systems provide synchronous delivery to destinations as a mechanism for implementing reliable applications. Some systems provide clients with various forms of delivery notification so that the clients can detect dropped or ignored messages. This is not the model defined by the JMS API. JMS API messaging provides guaranteed delivery via the once-and-only-once delivery semantics of PERSISTENT messages. In addition, message consumers can insure reliable processing of messages by using either CLIENT_ACKNOWLEDGE mode or transacted sessions. This achieves reliable delivery with minimum synchronization and is the enterprise messaging model most vendors and developers prefer. The JMS API does not define a schema of systems messages (such as delivery notifications). If an application requires acknowledgment of message receipt, it can define an application-level acknowledgment message.
- What are the core JMS-related objects required for each JMS-enabled application? - Each JMS-enabled client must establish the following:
- A connection object provided by the JMS server (the message broker)
- Within a connection, one or more sessions, which provide a context for message sending and receiving
- Within a session, either a queue or topic object representing the destination (the message staging area) within the message broker
- Within a session, the appropriate sender or publisher or receiver or subscriber object (depending on whether the client is a message producer or consumer and uses a point-to-point or publish/subscribe strategy, respectively). Within a session, a message object (to send or to receive)
- What is the Role of the JMS Provider? - The JMS provider handles security of the messages, data conversion and the client triggering. The JMS provider specifies the level of encryption and the security level of the message, the best data type for the non-JMS client.
- How does a typical client perform the communication? -
- Use JNDI to locate administrative objects.
- Locate a single ConnectionFactory object.
- Locate one or more Destination objects.
- Use the ConnectionFactory to create a JMS Connection.
- Use the Connection to create one or more Session(s).
- Use a Session and the Destinations to create the MessageProducers and MessageConsumers needed.
- Perform your communication.
- Give an example of using the point-to-point model. - The point-to-point model is used when the information is specific to a single client. For example, a client can send a message for a print out, and the server can send information back to this client after completion of the print job.
- How does the Application server handle the JMS Connection? -
- App server creates the server session and stores them in a pool.
- Connection consumer uses the server session to put messages in the session of the JMS.
- Server session is the one that spawns the JMS session.
- Applications written by Application programmers creates the message listener.
J2EE Interview Questions
- What makes J2EE suitable for distributed multitiered Applications?
- The J2EE platform uses a multitiered distributed application model. Application logic is divided into components according to function, and the various application components that make up a J2EE application are installed on different machines depending on the tier in the multitiered J2EE environment to which the application component belongs. The J2EE application parts are:- Client-tier components run on the client machine.
- Web-tier components run on the J2EE server.
- Business-tier components run on the J2EE server.
- Enterprise information system (EIS)-tier software runs on the EIS server.
- What is J2EE? - J2EE is an environment for developing and deploying enterprise applications. The J2EE platform consists of a set of services, application programming interfaces (APIs), and protocols that provide the functionality for developing multitiered, web-based applications.
- What are the components of J2EE application?
- A J2EE component is a self-contained functional software unit that is assembled into a J2EE application with its related classes and files and communicates with other components. The J2EE specification defines the following J2EE components:
- Application clients and applets are client components.
- Java Servlet and JavaServer Pages technology components are web components.
- Enterprise JavaBeans components (enterprise beans) are business components.
- Resource adapter components provided by EIS and tool vendors.
- What do Enterprise JavaBeans components contain? - Enterprise JavaBeans components contains Business code, which is logic
that solves or meets the needs of a particular business domain such as banking, retail, or finance, is handled by enterprise beans running in the business tier. All the business code is contained inside an Enterprise Bean which receives data from client programs, processes it (if necessary), and sends it to the enterprise information system tier for storage. An enterprise bean also retrieves data from storage, processes it (if necessary), and sends it back to the client program. - Is J2EE application only a web-based? - No, It depends on type of application that client wants. A J2EE application can be web-based or non-web-based. if an application client executes on the client machine, it is a non-web-based J2EE application. The J2EE application can provide a way for users to handle tasks such as J2EE system or application administration. It typically has a graphical user interface created from Swing or AWT APIs, or a command-line interface. When user request, it can open an HTTP connection to establish communication with a servlet running in the web tier.
- Are JavaBeans J2EE components? - No. JavaBeans components are not considered J2EE components by the J2EE specification. They are written to manage the data flow between an application client or applet and components running on the J2EE server or between server components and a database. JavaBeans components written for the J2EE platform have instance variables and get and set methods for accessing the data in the instance variables. JavaBeans components used in this way are typically simple in design and implementation, but should conform to the naming and design conventions outlined in the JavaBeans component architecture.
- Is HTML page a web component? - No. Static HTML pages and applets are bundled with web components during application assembly, but are not considered web components by the J2EE specification. Even the server-side utility classes are not considered web components, either.
- What can be considered as a web component? - J2EE Web components can be either servlets or JSP pages. Servlets are Java programming language classes that dynamically process requests and construct responses. JSP pages are text-based documents that execute as servlets but allow a more natural approach to creating static content.
- What is the container? - Containers are the interface between a component and the low-level platform specific functionality that supports the component. Before a Web, enterprise bean, or application client component can be executed, it must be assembled into a J2EE application and deployed into its container.
- What are container services? - A container is a runtime support of a system-level entity. Containers provide components with services such as lifecycle management, security, deployment, and threading.
- What is the web container? - Servlet and JSP containers are collectively referred to as Web containers. It manages the execution of JSP page and servlet components for J2EE applications. Web components and their container run on the J2EE server.
- What is Enterprise JavaBeans (EJB) container? - It manages the execution of enterprise beans for J2EE applications.
Enterprise beans and their container run on the J2EE server. - What is Applet container? - IManages the execution of applets. Consists of a Web browser and Java Plugin running on the client together.
- How do we package J2EE components? - J2EE components are packaged separately and bundled into a J2EE application for deployment. Each component, its related files such as GIF and HTML files or server-side utility classes, and a deployment descriptor are assembled into a module and added to the J2EE application. A J2EE application is composed of one or more enterprise bean,Web, or application client component modules. The final enterprise solution can use one J2EE application or be made up of two or more J2EE applications, depending on design requirements. A J2EE application and each of its modules has its own deployment descriptor. A deployment descriptor is an XML document with an .xml extension that describes a component’s deployment settings.
- What is a thin client? - A thin client is a lightweight interface to the application that does not have such operations like query databases, execute complex business rules, or connect to legacy applications.
- What are types of J2EE clients? - Following are the types of J2EE clients:
- Applets
- Application clients
- Java Web Start-enabled rich clients, powered by Java Web Start technology.
- Wireless clients, based on Mobile Information Device Profile (MIDP) technology.
- What is deployment descriptor? - A deployment descriptor is an Extensible Markup Language (XML) text-based file with an .xml extension that describes a component’s deployment settings. A J2EE application and each of its modules has its own deployment descriptor. For example, an enterprise bean module deployment descriptor declares transaction attributes and security authorizations
for an enterprise bean. Because deployment descriptor information is declarative, it can be changed without modifying the bean source code. At run time, the J2EE server reads the deployment descriptor and acts upon the component accordingly. - What is the EAR file? - An EAR file is a standard JAR file with an .ear extension, named from Enterprise ARchive file. A J2EE application with all of its modules is delivered in EAR file.
- What is JTA and JTS? - JTA is the abbreviation for the Java Transaction API. JTS is the abbreviation for the Jave Transaction Service. JTA provides a standard interface and allows you to demarcate transactions in a manner that is independent of the transaction manager implementation. The J2EE SDK implements the transaction manager with JTS. But your code doesn’t call the JTS methods directly. Instead, it invokes the JTA methods, which then call the lower-level JTS routines. Therefore, JTA is a high level transaction interface that your application uses to control transaction. and JTS is a low level transaction interface and ejb uses behind the scenes (client code doesn’t directly interact with JTS. It is based on object transaction service(OTS) which is part of CORBA.
- What is JAXP? - JAXP stands for Java API for XML. XML is a language for representing and describing text-based data which can be read and handled by any program or tool that uses XML APIs. It provides standard services to determine the type of an arbitrary piece of data, encapsulate access to it, discover the operations available on it, and create the appropriate JavaBeans component to perform those operations.
- What is J2EE Connector? - The J2EE Connector API is used by J2EE tools vendors and system integrators to create resource adapters that support access to enterprise information systems that can be plugged into any J2EE product. Each type of database or EIS has a different resource adapter. Note: A resource adapter is a software component that allows J2EE application components to access and interact with the underlying resource manager. Because a resource adapter is specific to its resource manager, there is typically a different resource adapter for each type of database or enterprise information system.
- What is JAAP? - The Java Authentication and Authorization Service (JAAS) provides a way for a J2EE application to authenticate and authorize a specific user or group of users to run it. It is a standard Pluggable Authentication Module (PAM) framework that extends the Java 2 platform security architecture to support user-based authorization.
- What is Java Naming and Directory Service? - The JNDI provides naming and directory functionality. It provides applications with methods for performing standard directory operations, such as associating attributes with objects and searching for objects using their attributes. Using JNDI, a J2EE application can store and retrieve any type of named Java object. Because JNDI is independent of any specific implementations, applications can use JNDI to access multiple naming and directory services, including existing naming and
directory services such as LDAP, NDS, DNS, and NIS. - What is Struts? - A Web page development framework. Struts combines Java Servlets, Java Server Pages, custom tags, and message resources into a unified framework. It is a cooperative, synergistic platform, suitable for development teams, independent developers, and everyone between.
- How is the MVC design pattern used in Struts framework? - In the MVC design pattern, application flow is mediated by a central Controller. The Controller delegates requests to an appropriate handler. The handlers are tied to a Model, and each handler acts as an adapter between the request and the Model. The Model represents, or encapsulates, an application’s business logic or state. Control is usually then forwarded back through the Controller to the appropriate View. The forwarding can be determined by consulting a set of mappings, usually loaded from a database or configuration file. This provides a loose coupling between the View and Model, which can make an application significantly easier to create and maintain. Controller: Servlet controller which supplied by Struts itself; View: what you can see on the screen, a JSP page and presentation components; Model: System state and a business logic JavaBeans.
Basic
Servlets Questions
- What is the difference between CGI and Servlet?
- What is meant by a servlet?
- What are the types of servlets? What is the difference between 2 types of Servlets?
- What is the type of method for sending request from HTTP server ?
- What are the exceptions thrown by Servlets? Why?
- What is the life cycle of a servlet?
- What is meant by cookies? Why is Cookie used?
- What is HTTP Session?
- What is the difference between GET and POST methods?
- How can you run a Servlet Program?
- What is the middleware? What is the functionality of Webserver?
- What webserver is used for running the Servlets?
- How do you invoke a Servelt? What is the difference in between doPost and doGet methods?
- What is the difference in between the HTTPServlet and Generic Servlet? Explain their methods? Tell me their parameter names also?
- What are session variable in Servlets?
- What is meant by Session? Tell me something about HTTPSession Class?
- What is Session Tracking?
- Difference between doGet and doPost?
- What are the methods in HttpServlet?
- What are the types of SessionTracking? Why do you use Session Tracking in HttpServlet?
Servlets Interview Question
- What is a servlet?
Servlets are modules that extend request/response-oriented servers,such as Java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database. Servlets are to servers what applets are to browsers. Unlike applets, however, servlets have no graphical user interface. - Whats the advantages using servlets over using CGI?
Servlets provide a way to generate dynamic documents that is both easier to write and faster to run. Servlets also address the problem of doing server-side programming with platform-specific APIs: they are developed with the Java Servlet API, a standard Java extension. - What are the general advantages and selling points of Servlets?
A servlet can handle multiple requests concurrently, and synchronize requests. This allows servlets to support systems such as online
real-time conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task type or organizational boundaries. - Which package provides interfaces and classes for writing servlets? javax
- What’s the Servlet Interface?
The central abstraction in the Servlet API is the Servlet interface. All servlets implement this interface, either directly or, more
commonly, by extending a class that implements it such as HttpServlet.Servlets > Generic Servlet > HttpServlet > MyServlet.
The Servlet interface declares, but does not implement, methods that manage the servlet and its communications with clients. Servlet writers provide some or all of these methods when developing a servlet. - When a servlet accepts a call from a client, it receives two objects. What are they?
ServletRequest (which encapsulates the communication from the client to the server) and ServletResponse (which encapsulates the communication from the servlet back to the client). ServletRequest and ServletResponse are interfaces defined inside javax.servlet package. - What information does ServletRequest allow access to?
Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names
of the remote host that made the request and the server that received it. Also the input stream, as ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and GET methods. - What type of constraints can ServletResponse interface set on the client?
It can set the content length and MIME type of the reply. It also provides an output stream, ServletOutputStream and a Writer through
which the servlet can send the reply data. - Explain servlet lifecycle?
Each servlet has the same life cycle: first, the server loads and initializes the servlet (init()), then the servlet handles zero or more client requests (service()), after that the server removes the servlet (destroy()). Worth noting that the last step on some servers is done when they shut down. - How does HTTP Servlet handle client requests?
An HTTP Servlet handles client requests through its service method. The service method supports standard HTTP client requests by dispatching each request to a method designed to handle that request.
XJDBC
Interview Question
- What are the steps involved in establishing a JDBC connection? This action involves two steps: loading the JDBC driver and making the connection.
- How can you load the drivers?
Loading the driver or drivers you want to use is very simple and involves just one line of code. If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Your
driver documentation will give you the class name to use. For
instance, if the class name is jdbc.DriverXYZ, you would load the
driver with the following line of code:
Class.forName("jdbc.DriverXYZ");
- What will Class.forName do while loading drivers? It is used to create an instance of a driver and register it with the
DriverManager. When you have loaded a driver, it is available for making a connection with a DBMS. - How can you make the connection? To establish a connection you need to have the appropriate driver connect to the DBMS.
The following line of code illustrates the general idea:
String url =
“jdbc:odbc:Fred";
Connection con = DriverManager.getConnection(url, “Fernanda", “J8?);
Connection con = DriverManager.getConnection(url, “Fernanda", “J8?);
- How can you create JDBC statements and what are they?
A Statement object is what sends your SQL statement to the DBMS. You simply create a Statement object and then execute it, supplying the appropriate execute method with the SQL statement you want to send. For a SELECT statement, the method to use is executeQuery. For statements that create or modify tables, the method to use is executeUpdate. It takes an instance of an active connection to create a Statement object. In the following example, we use our Connection object con to create the Statement object
Statement stmt =
con.createStatement();
- How can you retrieve data from the ResultSet?
JDBC returns results in a ResultSet object, so we need to declare an instance of the class ResultSet to hold our results. The following code demonstrates declaring the ResultSet object rs.
ResultSet rs =
stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
String s = rs.getString("COF_NAME");
String s = rs.getString("COF_NAME");
The
method getString is invoked on the ResultSet object rs, so
getString() will retrieve (get) the value stored in the column
COF_NAME in the current row of rs.
- What are the different types of Statements?
Regular statement (use createStatement method), prepared statement (use prepareStatement method) and callable statement (use prepareCall) - How can you use PreparedStatement? This special type of statement is derived from class Statement.If you need a
Statement object to execute many times, it will normally make sense to use a PreparedStatement object instead. The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement’s SQL statement without having to compile it first. - PreparedStatement updateSales =
- con.prepareStatement("UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
- What does setAutoCommit do?
When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode:
con.setAutoCommit(false);
Once
auto-commit mode is disabled, no SQL statements will be committed
until you call the method commit explicitly.
con.setAutoCommit(false);
PreparedStatement
updateSales =
con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt(1,
50); updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement
updateTotal =
con.prepareStatement("UPDATE
COFFEES SET TOTAL = TOTAL + ? WHERE COF_NAME LIKE ?");
updateTotal.setInt(1,
50);
updateTotal.setString(2,
"Colombian");
updateTotal.executeUpdate();
con.commit();
con.setAutoCommit(true);
- How do you call a stored procedure from JDBC?
The first step is to create a CallableStatement object. As with Statement an and PreparedStatement objects, this is done with an open
Connection object. A CallableStatement object contains a call to a stored procedure. - CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
- ResultSet rs = cs.executeQuery();
- How do I retrieve warnings?
SQLWarning objects are a subclass of SQLException that deal with database access warnings. Warnings do not stop the execution of an
application, as exceptions do; they simply alert the user that something did not happen as planned. A warning can be reported on a
Connection object, a Statement object (including PreparedStatement and CallableStatement objects), or a ResultSet object. Each of these
classes has a getWarnings method, which you must invoke in order to see the first warning reported on the calling object: - SQLWarning warning = stmt.getWarnings();
- if (warning != null)
- {
- System.out.println("n---Warning---n");
- while (warning != null)
- {
- System.out.println("Message: " + warning.getMessage());
- System.out.println("SQLState: " + warning.getSQLState());
- System.out.print("Vendor error code: ");
- System.out.println(warning.getErrorCode());
- System.out.println("");
- warning = warning.getNextWarning();
- }
- }
- How can you move the cursor in scrollable result sets?
One of the new features in the JDBC 2.0 API is the ability to move a result set’s cursor backward as well as forward. There are also methods that let you move the cursor to a particular row and check the position of the cursor.
Statement stmt =
con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
ResultSet srs = stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
The
first argument is one of three constants added to the ResultSet API
to indicate the type of a ResultSet object: TYPE_FORWARD_ONLY,
TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE. The second
argument is one of two ResultSet constants for specifying whether a
result set is read-only or updatable: CONCUR_READ_ONLY and
CONCUR_UPDATABLE. The point to remember here is that if you specify a
type, you must also specify whether it is read-only or updatable.
Also, you must specify the type first, and because both parameters
are of type int , the compiler will not complain if you switch the
order. Specifying the constant TYPE_FORWARD_ONLY creates a
nonscrollable result set, that is, one in which the cursor moves only
forward. If you do not specify any constants for the type and
updatability of a ResultSet object, you will automatically get one
that is TYPE_FORWARD_ONLY and CONCUR_READ_ONLY.
- What’s the difference between TYPE_SCROLL_INSENSITIVE , and TYPE_SCROLL_SENSITIVE?
You will get a scrollable ResultSet object if you specify one of these ResultSet constants.The difference between the two has to do with whether a result set reflects changes that are made to it while it is open and whether certain methods can be called to detect these changes. Generally speaking, a result set that is TYPE_SCROLL_INSENSITIVE does not reflect changes made while it is still open and one that is TYPE_SCROLL_SENSITIVE does. All three types of result sets will make changes visible if they are closed and then reopened: - Statement stmt =
- con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
- ResultSet srs =
- stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
- srs.afterLast();
- while (srs.previous())
- {
- String name = srs.getString("COF_NAME");
- float price = srs.getFloat("PRICE");
- System.out.println(name + " " + price);
- }
- How to Make Updates to Updatable Result Sets?
Another new feature in the JDBC 2.0 API is the ability to update rows in a result set using methods in the Java programming language rather than having to send an SQL command. But before you can take advantage of this capability, you need to create a ResultSet object that is updatable. In order to do this, you supply the ResultSet constant CONCUR_UPDATABLE to the createStatement method. - Connection con =
- DriverManager.getConnection("jdbc:mySubprotocol:mySubName");
- Statement stmt =
- con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
- ResultSet uprs =
- stmt.executeQuery("SELECT COF_NAME, PRICE FROM COFFEES");
No comments:
Post a Comment