Java database connectivity (JDBC) is an API that enables Java programs to execute SQL statements. If you are attending an interview related to JDBC, you need to gain knowledge on different aspects of the subject. Every job seeker is unsure about the JDBC interview questions and answers he/ she is going to encounter during the interview process. Gaining some information on the same would make getting placed an easy job for the job seeker. Let wisdomjobs.com help you in this regard. Reach the portal to know various job interview questions and answers that you are going to encounter during the process and give a thorough preparation in this regard to win the competitions. A well-researched set of questions framed here will give you the exposure to the skill set the interviewer is looking for to hire you for the job.
Answer :
Java Database Connectivity (JDBC) is a standard Java API to interact with relational databases form Java. JDBC has set of classes and interfaces which can use from Java application and talk to database without learning RDBMS details and using Database Specific JDBC Drivers.
Question 2. What Are The New Features Added To Jdbc 4.0?
Answer :
The major features added in JDBC 4.0 include :
Question 3. Explain Basic Steps In Writing A Java Program Using Jdbc?
Answer :
JDBC makes the interaction with RDBMS simple and intuitive. When a Java application needs to access database :
Question 4. What Are The Main Components Of Jdbc ?
Answer :
The life cycle of a servlet consists of the following phases:
Question 5. What Is Jdbc Driver Interface?
Answer :
The JDBC Driver interface provides vendor-specific implementations of the abstract classes provided by the JDBC API. Each vendor driver must provide implementations of the java.sql.Connection, Statement, Prepared Statement, CallableStatement, ResultSet and Driver.
Question 6. What Does The Connection Object Represents?
Answer :
The connection object represents communication context, i.e., all communication with database is through connection object only.
Question 7. What Is Statement ?
Answer :
Question 8. What Is Preparedstatement?
Answer :
A prepared statement is an SQL statement that is precompiled by the database. Through precompilation, prepared statements improve the performance of SQL commands that are executed multiple times (given that the database supports prepared statements). Once compiled, prepared statements can be customized prior to each execution by altering predefined SQL parameters.
PreparedStatement pstmt = conn.prepareStatement("UPDATE EMPLOYEES SET SALARY = ? WHERE ID = ?");
pstmt.setBigDecimal(1, 153833.00);
pstmt.setInt(2, 110592);
Here: conn is an instance of the Connection class and "?" represents parameters.These parameters must be specified before execution.
Question 9. What Are Callable Statements ?
Answer :
Callable statements are used from JDBC application to invoke stored procedures and functions.
Question 10. How To Call A Stored Procedure From Jdbc ?
Answer :
PL/SQL stored procedures are called from within JDBC programs by means of the prepareCall() method of the Connection object created. A call to this method takes variable bind parameters as input parameters as well as output variables and creates an object instance of the CallableStatement class. The following line of code illustrates this:
CallableStatement stproc_stmt = conn.prepareCall("{call procname(?,?,?)}");
Here conn is an instance of the Connection class.
Question 11. What Are Types Of Jdbc Drivers?
Answer :
There are four types of drivers defined by JDBC as follows:
Question 12. Which Type Of Jdbc Driver Is The Fastest One?
Answer :
JDBC Net pure Java driver(Type IV) is the fastest driver because it converts the JDBC calls into vendor specific protocol calls and it directly interacts with the database.
Question 13. Does The Jdbc-odbc Bridge Support Multiple Concurrent Open Statements Per Connection?
Answer :
No. You can open only one Statement object per connection when you are using the JDBC-ODBC Bridge.
Question 14. Which Is The Right Type Of Driver To Use And When?
Answer :
Question 15. What Are The Standard Isolation Levels Defined By Jdbc?
Answer :
The values are defined in the class java.sql.Connection and are:
Any given database may not support all of these levels.
Question 16. What Is Resultset ?
Answer :
The ResultSet represents set of rows retrieved due to query execution.
ResultSet rs = stmt.executeQuery(sqlQuery);
Answer :
A RowSet is an object that encapsulates a set of rows from either Java Database Connectivity (JDBC) result sets or tabular data sources like a file or spreadsheet. RowSets support component-based development models like JavaBeans, with a standard set of properties and an event notification .
Question 18. What Are The Different Types Of Rowset ?
Answer :
There are two types of RowSet are there. They are:
Question 19. What Is The Need Of Batchupdates?
Answer :
The BatchUpdates feature allows us to group SQL statements together and send to database server in one single trip.
Question 20. What Is A Datasource?
Answer :
A DataSource object is the representation of a data source in the Java programming language. In basic terms,
Question 21. What Is Connection Pooling? What Is The Main Advantage Of Using Connection Pooling?
Answer :
A connection pool is a mechanism to reuse connections created. Connection pooling can increase performance dramatically by reusing connections rather than creating a new physical connection each time a connection is requested.
Question 22. What's The Jdbc 3.0 Api?
Answer :
The JDBC 3.0 API is the latest update of the JDBC API. It contains many features, including scrollable result sets and the SQL:1999 data types.
JDBC (Java Database Connectivity) is the standard for communication between a Java application and a relational database. The JDBC API is released in two versions; JDBC version 1.22 (released with JDK 1.1.X in package java.sql) and version 2.0 (released with Java platform 2 in packages java.sql and javax.sql). It is a simple and powerful largely database-independent way of extracting and inserting data to or from any database.
Question 23. Does The Jdbc-odbc Bridge Support The New Features In The Jdbc 3.0 Api?
Answer :
The JDBC-ODBC Bridge provides a limited subset of the JDBC 3.0 API.
Question 24. Can The Jdbc-odbc Bridge Be Used With Applets?
Answer :
Use of the JDBC-ODBC bridge from an untrusted applet running in a browser, such as Netscape Navigator, isn't allowed. The JDBC-ODBC bridge doesn't allow untrusted code to call it for security reasons. This is good because it means that an untrusted applet that is downloaded by the browser can't circumvent Java security by calling ODBC. Remember that ODBC is native code, so once ODBC is called the Java programming language can't guarantee that a security violation won't occur. On the other hand, Pure Java JDBC drivers work well with applets. They are fully downloadable and do not require any client-side configuration.
Finally, we would like to note that it is possible to use the JDBC-ODBC bridge with applets that will be run in appletviewer since appletviewer assumes that applets are trusted. In general, it is dangerous to turn applet security off, but it may be appropriate in certain controlled situations, such as for applets that will only be used in a secure intranet environment. Remember to exercise caution if you choose this option, and use an all-Java JDBC driver whenever possible to avoid security problems.
Question 25. How Do I Start Debugging Problems Related To The Jdbc Api?
Answer :
A good way to find out what JDBC calls are doing is to enable JDBC tracing. The JDBC trace contains a detailed listing of the activity occurring in the system that is related to JDBC operations.
If you use the DriverManager facility to establish your database connection, you use the DriverManager. setLogWriter method to enable tracing of JDBC operations. If you use a DataSource object to get a connection, you use the DataSource.setLogWriter method to enable tracing. (For pooled connections, you use the ConnectionPoolDataSource.setLogWriter method, and for connections that can participate in distributed transactions, you use the XADataSource.setLogWriter method.)
Question 26. What Is New In Jdbc 2.0?
Answer :
With the JDBC 2.0 API, you will be able to do the following:
Scroll forward and backward in a result set or move to a specific row (TYPE_SCROLL_ SENSITIVE, previous(), last(), absolute(), relative(), etc.) Make updates to database tables using methods in the Java programming language instead of using SQL commands.(updateRow(), insertRow(), deleteRow(), etc.) Send multiple SQL statements to the database as a unit, or batch (addBatch(), executeBatch()) Use the new SQL3 datatypes as column values like Blob, Clob, Array, Struct, Ref.
Question 27. How Many Types Of Jdbc Drivers Are Present And What Are They?
Answer :
There are 4 types of JDBC Drivers
Question 28. Can We Implement An Interface In A Jsp?
Answer :
No
Question 29. What Is The Difference Between Servletcontext And Pagecontext?
Answer :
ServletContext: Gives the information about the container.
PageContext: Gives the information about the Request.
Question 30. How To Pass Information From Jsp To Included Jsp?
Answer :
Using <%jsp:param> tag.
Question 31. What Is The Difference Between Directive Include And Jsp Include?
Answer :
<%@ include>: Used to include static resources during translation time.
JSP include: Used to include dynamic content or static content during runtime.
Question 32. What Is The Difference Between Requestdispatcher And Sendredirect?
Answer :
RequestDispatcher: server-side redirect with request and response objects.
sendRedirect : Client-side redirect with new request and response objects.
Question 33. How Does Jsp Handle Runtime Exceptions?
Answer :
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.
Question 34. How Do You Delete A Cookie Within A Jsp?
Answer :
Cookie mycook = new Cookie("name","value");
response.addCookie(mycook);
Cookie killmycook = new Cookie("mycook","value");
killmycook.setMaxAge(0);
killmycook.setPath("/");
killmycook.addCookie(killmycook);
Question 35. How Do I Mix Jsp And Ssi #include?
Answer :
If you’re just including raw HTML, use the #include directive as usual inside your .jsp file.
Question 36. I Made My Class Cloneable But I Still Get Can't Access Protected Method Clone. Why?
Answer :
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().
Question 37. Why Is Xml Such An Important Development?
Answer :
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.
Question 38. What Is The Fastest Type Of Jdbc Driver?
Answer :
JDBC driver performance will depend on a number of issues:
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).
Question 39. How Do I Find Whether A Parameter Exists In The Request Object?
Answer :
boolean hasFoo = !(request.getParameter("foo") == null
|| request.getParameter("foo").equals(""));
or
boolean hasParameter =
request.getParameterMap().contains(theParameter); //(which works in Servlet 2.3+)
Question 40. How Can I Send User Authentication Information While Makingurlconnection?
Answer :
You’ll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.
Question 41. How Do I Create A Database Connection?
Answer :
The database connection is created in 3 steps:
In java code, the steps are realized in code as follows:
Class.forName("my.database.driver");
}
catch(Exception ex)
{
System.err.println("Could not load database driver: " + ex);
}
Question 42. What Is Metadata And Why Should I Use It?
Answer :
Metadata ('data about data') is information about one of two things:
Use DatabaseMetaData to find information about your database, such as its capabilities and structure. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns.
Question 43. How Does The Java Database Connectivity (jdbc) Work?
Answer :
The JDBC is used whenever a Java application should communicate with a relational database for which a JDBC driver exists. JDBC is part of the Java platform standard; all visible classes used in the Java/database communication are placed in package java.sql.
Main JDBC classes:
Question 44. What Is The Advantage Of Using A Preparedstatement?
Answer :
For SQL statements that are executed repeatedly, using a PreparedStatement object would almost always be faster than using a Statement object. This is because creating a PreparedStatement object by explicitly giving the SQL statement causes the statement to be precompiled within the database immediately. Thus, when the PreparedStatement is later executed, the DBMS does not have to recompile the SQL statement and prepared an execution plan - it simply runs the statement.
Typically, PreparedStatement objects are used for SQL statements that take parameters. However, they can also be used with repeatedly executed SQL statements that do not accept parameters.
Answer :
The operation is performed in 9 steps:
Answer :
A ResultSet is an interface. Its implementation depends on the driver and hence ,what it "contains" depends partially on the driver and what the query returns. For example with the Odbc bridge what the underlying implementation layer contains is an ODBC result set. A Type 4 driver executing a stored procedure that returns a cursor - on an oracle database it actually returns a cursor in the databse. The oracle cursor can however be processed like a ResultSet would be from the client. Closing a connection closes all interaction with the database and releases any locks that might have been obtained in the process.
Question 47. Can I Use The Jdbc-odbc Bridge Driver In An Applet?
Answer :
No.
Question 48. How Can I Connect From An Applet To A Database On The Server?
Answer :
There are two ways of connecting to a database on the server side.
Question 49. How Do I Insert An Image File (or Other Raw Data) Into A Database?
Answer :
All raw data types (including binary documents or images) should be read and uploaded to the database as an array of bytes, byte[]. Originating from a binary file,
Question 50. How Can Resultset Records Be Restricted To Certain Rows?
Answer :
The easy answer is "Use a JDBC 2.0 compliant driver". With a 2.0 driver, you can use the setFetchSize() method within a Statement or a ResultSet object.
For example,
Statement stmt = con.createStatement();
stmt.setFetchSize(400);
ResultSet rs = stmt.executeQuery("select * from customers");
will change the default fetch size to 400.
You can also control the direction in which the rows are processed. For instance:
stmt.setFetchDirection(ResultSet.FETCH_REVERSE)
will process the rows from bottom up.
The driver manager usually defaults to the most efficient fetch size...so you may try experimenting with different value for optimal performance.
Question 51. What Is The Difference Between Client And Server Database Cursors?
Answer :
What you see on the client side is the current row of the cursor which called a Result (ODBC) or ResultSet (JDBC). The cursor is a server-side entity only and remains on the server side.
Question 52. How Can I Convert A Java Array To A Java.sql.array?
Answer :
A Java array is a first class object and all of the references basically use PreparedStatement.setObject() or ResultSet.updateObject() methods for putting the array to an ARRAY in the database. Here's a basic example:
String[] as = { "One", "Two", "Three" };
...
PreparedStatement ps = con.prepareStatement(
"UPDATE MYTABLE SET ArrayNums = ? WHERE MyKey = ?" );
...
ps.setObject( 1, as );
Question 53. How Can I Insert Multiple Rows Into A Database In A Single Transaction?
Answer :
//turn off the implicit commit
Connection.setAutoCommit(false);
//..your insert/update/delete goes here
Connection.Commit();
a new transaction is implicitly started. JDBC 2.0 provides a set of methods for executing a batch of database commands. Specifically, the java. sql. Statement interface provides three methods: addBatch(), clearBatch() and executeBatch(). Their documentation is pretty straight forward. The implementation of these methods is optional, so be sure that your driver supports these.
Question 54. How Can I Connect To An Oracle Database Not On The Web Server From An Untrusted Applet?
Answer :
You can use the thin ORACLE JDBC driver in an applet (with some extra parameters on the JDBC URL). Then, if you have NET8, you can use the connection manager of NET8 on the web server to proxy the connection request to the database server.
Question 55. How Do I Get Runtime Information About The Jdbc Driver?
Answer :
Use the following DatabaseMetaData methods:
getDriverMajorVersion()
getDriverMinorVersion()
getDriverName()
getDriverVersion()
Answer :
Use the DatabaseMetaData methods supportsOpen StatementsAcrossCommit() and supports Open Statements Across Rollback().
Answer :
While the specification makes no mention of any size limitation for Statement.addBatch(), this seems to be dependent, as usual, on the driver. Among other things, it depends on the type of container/collection used. I know of at least one driver that uses a Vector and grows as needed. I've seen questions about another driver that appears to peak somewhere between 500 and 1000 statements. Unfortunately, there doesn't appear to be any metadata information regarding possible limits. Of course, in a production quality driver, one would expect an exception from an addBatch() invocation that went beyond the command list's limits.
Question 58. What Does Setfetchsize() Really Do?
Answer :
The API documentation explains it pretty well, but a number of programmers seem to have a misconception of its functionality. The first thing to note is that it may do nothing at all; it is only a hint, even to a JDBC Compliant driver. setFetchSize() is really a request for a certain sized blocking factor, that is, how much data to send at a time.
Because trips to the server are expensive, sending a larger number of rows can be more efficient. It may be more efficient on the server side as well, depending on the particular SQL statement and the DB engine. That would be true if the data could be read straight off an index and the DB engine paid attention to the fetch size. In that case, the DB engine could return only enough data per request to match the fetch size. Don't count on that behavior. In general, the fetch size will be transparent to your program and only determines how often requests are sent to the server as you traverse the data. Also, both Statement and ResultSet have setFetchSize methods. If used with a Statement, all ResultSets returned by that Statement will have the same fetch size. The method can be used at any time to change the fetch size for a given ResultSet. To determine the current or default size, use the getFetchSize methods.
Question 59. What Scalar Functions Can I Expect To Be Supported By Jdbc?
Answer :
JDBC supports numeric, string, time, date, system, and conversion functions on scalar values. For a list of those supported and additional information, see section A.1.4 Support Scalar Functions in the JDBC Data Access API For Driver Writers. Note that drivers are only expected to support those scalar functions that are supported by the underlying DB engine.
Question 60. What Does Normalization Mean For Java.sql.date And Java.sql.time?
Answer :
These classes are thin wrappers extending java.util.Date, which has both date and time components. java.sql.Date should carry only date information and a normalized instance has the time information set to zeros. java.sql.Time should carry only time information and a normalized instance has the date set to the Java epoch ( January 1, 1970 ) and the milliseconds portion set to zero.
Question 61. What Jdbc Objects Generate Sqlwarnings?
Answer :
Connections, Statements and ResultSets all have a getWarnings method that allows retrieval. Keep in mind that prior ResultSet warnings are cleared on each new read and prior Statement warnings are cleared with each new execution. getWarnings() itself does not clear existing warnings, but each object has a clearWarnings method.
Question 62. How Can I Investigate The Physical Structure Of A Database?
Answer :
The JDBC view of a database internal structure can be seen in the image below.
The DatabaseMetaData interface has methods for discovering all the Catalogs, Schemas, Tables and Stored Procedures in the database server. The methods are pretty intuitive, returning a ResultSet with a single String column; use them as indicated in the code below:
public static void main(String[] args) throws Exception
{
// Load the database driver - in this case, we
// use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Open a connection to the database
Connection conn = DriverManager.getConnection("[jdbcURL]", "[login]", "[passwd]");
// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();
// Get all Catalogs
System.out.println("nCatalogs are called '" + dbmd.getCatalogTerm()
+ "' in this RDBMS.");
processResultSet(dbmd.getCatalogTerm(), dbmd.getCatalogs());
// Get all Schemas
System.out.println("nSchemas are called '" + dbmd.getSchemaTerm()
+ "' in this RDBMS.");
processResultSet(dbmd.getSchemaTerm(), dbmd.getSchemas());
// Get all Table-like types
System.out.println("nAll table types supported in this RDBMS:");
processResultSet("Table type", dbmd.getTableTypes());
// Close the Connection
conn.close();
}
public static void processResultSet(String preamble, ResultSet rs)
throws SQLException
{
// Printout table data
while(rs.next())
{
// Printout
System.out.println(preamble + ": " + rs.getString(1));
}
// Close database resources
rs.close();
}
Question 63. How Do I Find All Database Stored Procedures In A Database?
Answer :
Use the getProcedures method of interface java.sql.DatabaseMetaData to probe the database for stored procedures. The exact usage is described in the code below.
public static void main(String[] args) throws Exception
{
// Load the database driver - in this case, we
// use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Open a connection to the database
Connection conn = DriverManager.getConnection("[jdbcURL]", "[login]", "[passwd]");
// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();
// Get all procedures.
System.out.println("Procedures are called '" + dbmd.getProcedureTerm() +"' in the DBMS.");
ResultSet rs = dbmd.getProcedures(null, null, "%");
// Printout table data
while(rs.next())
{
// Get procedure metadata
String dbProcedureCatalog = rs.getString(1);
String dbProcedureSchema = rs.getString(2);
String dbProcedureName = rs.getString(3);
String dbProcedureRemarks = rs.getString(7);
short dbProcedureType = rs.getShort(8);
// Make result readable for humans
String procReturn = (dbProcedureType == DatabaseMetaData.procedureNoResult ? "No Result" : "Result");
// Printout
System.out.println("Procedure: " + dbProcedureName + ", returns: " + procReturn);
System.out.println(" [Catalog | Schema]: [" + dbProcedureCatalog + " | " + dbProcedureSchema + "]");
System.out.println(" Comments: " + dbProcedureRemarks);
}
// Close database resources
rs.close();
conn.close();
}
Question 64. How Do I Check What Table Types Exist In A Database?
Answer :
Use the getTableTypes method of interface java.sql.DatabaseMetaData to probe the database for table types. The exact usage is described in the code below.
public static void main(String[] args) throws Exception
{
// Load the database driver - in this case, we
// use the Jdbc/Odbc bridge driver.
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Open a connection to the database
Connection conn = DriverManager.getConnection("[jdbcURL]", "[login]", "[passwd]");
// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.getMetaData();
// Get all table types.
ResultSet rs = dbmd.getTableTypes();
// Printout table data
while(rs.next())
{
// Printout
System.out.println("Type: " + rs.getString(1));
}
// Close database resources
rs.close();
conn.close();
}
Question 65. How Do I Extract A Blob From A Database?
Answer :
A BLOB (Binary Large OBject) is essentially an array of bytes (byte[]), stored in the database. You extract the data in two steps:
Note that a Blob is essentially a pointer to a byte array (called LOCATOR in database-talk), so the java.sql.Blob object essentially wraps a byte pointer. Thus, you must extract all data from the database blob before calling commit or
<div align="center">
private void runGetBLOB()
{
try
{ // Prepare a Statement:
PreparedStatement stmnt = conn.prepareStatement("select aBlob from BlobTable");
// Execute
ResultSet rs = stmnt.executeQuery();
while(rs.next())
{
try
{
// Get as a BLOB
Blob aBlob = rs.getBlob(1);
byte[] allBytesInBlob = aBlob.getBytes(1, (int) aBlob.length());
}
catch(Exception ex)
{
// The driver could not handle this as a BLOB...
// Fallback to default (and slower) byte[] handling
byte[] bytes = rs.getBytes(1);
}
}
// Close resources rs.close();
stmnt.close();
}
catch(Exception ex)
{
this.log("Error when trying to read BLOB: " + ex);
}
}</div>
Question 66. Which Is The Preferred Collection Class To Use For Storing Database Result Sets?
Answer :
When retrieving database results, the best collection implementation to use is the LinkedList. The benefits include:
Basically:
ResultSet result = stmt.executeQuery("...");
List list = new LinkedList();
while(result.next()) {
list.add(result.getString("col"));
}
If there are multiple columns in the result set, you'll have to combine them into their own data structure for each row. Arrays work well for that as you know the size, though a custom class might be best so you can convert the contents to the proper type when extracting from databse, instead of later.
Question 67. How Can I Get Data From Multiple Resultsets?
Answer :
With certain database systems, a stored procedure can return multiple result sets, multiple update counts, or some combination of both. Also, if you are providing a user with the ability to enter any SQL statement, you don't know if you are going to get a ResultSet or an update count back from each statement, without analyzing the contents. The Statement.execute() method helps in these cases.
Method Statement.execute() returns a boolean to tell you the type of response:
Use Statement.getResultSet to get the ResultSet
Use Statement.getUpdateCount to get the update count
Update count is -1 when no more results (usually 0 or positive)
After processing each response, you use Statement.getMoreResults to check for more results, again returning a boolean. The following demonstrates the processing of multiple result sets:
boolean result = stmt.execute(" ... ");
int updateCount = stmt.getUpdateCount();
while (result || (updateCount != -1)) {
if(result) {
ResultSet r = stmt.getResultSet();
// process result set
} else if(updateCount != -1) {
// process update count
}
result = stmt.getMoreResults();
updateCount = stmt.getUpdateCount();
}
Answer :
Briefly: jdbc:oracle:thin:@hostname:port:oracle-sid
example:
jdbc:oracle:thin:@MyOracleHost:1521:MyDB
Here's an example:
jdbc:oracle:thin:scott/tiger@MyOracleHost:1521:MyDB
where user=scott and pass=tiger.
Answer :
One possibility: Have an optional field in your form or GET url called (appropriately) ORDER with a default value of either "no order" or whatever you want your default ordering to be (i.e. timestamp, username, whatever). When you get your request, see what the value of the ORDER element is. If it's null or blank, use the default. Use that value to build your SQL query, and display the results to the page. If you're caching data in your servlet, you can use the Collection framework to sort your data (see java.util.Collections) if you can get it into a List format. Then, you can create a Collator which can impose a total ordering on your results.
Answer :
Because PreparedStatement objects are precompiled, their execution can be faster than that of Statement objects. Consequently, an SQL statement that is executed many times is often created as a PreparedStatement object to increase efficiency. A CallableStatement object provides a way to call stored procedures in a standard manner for all DBMSes. Their execution can be faster than that of PreparedStatement object. Batch updates are used when you want to execute multiple statements together. Actually, there is no conflict here. While it depends on the driver/DBMS engine as to whether or not you will get an actual performance benefit from batch updates, Statement, PreparedStatement, and CallableStatement can all execute the addBatch() method.
Answer :
JDO provides for the transparent persistence of data in a data store agnostic manner, supporting object, hierarchical, as well as relational stores.
Answer :
setFetchSize(int) defines the number of rows that will be read from the database when the ResultSet needs more rows. The method in the java.sql.Statement interface will set the 'default' value for all the ResultSet derived from that Statement; the method in the java.sql.ResultSet interface will override that value for a specific ResultSet. Since database fetches can be expensive in a networked environment, fetch size has an impact on performance.
setMaxRows(int) sets the limit of the maximum nuber of rows in a ResultSet object. If this limit is exceeded, the excess rows are "silently dropped". That's all the API says, so the setMaxRows method may not help performance at all other than to decrease memory usage. A value of 0 (default) means no limit. Since we're talking about interfaces, be careful because the implementation of drivers is often different from database to database and, in some cases, may not be implemented or have a null implementation. Always refer to the driver documentation.
Question 73. How Can I Tell If My Jdbc Driver Normalizes Java.sql.date And Java.sql.time Objects?
Answer :
To actually determine the values, the objects must be converted to a java.util.Date and examined. See What does normalization mean for java.sql.Date and java.sql.Time? for the definition of normalization. Notice that even a debugger will not show whether these objects have been normalized, since the getXXX methods in java.sql.Date for time elements and in java.sql.Time for date elements throw an exception.
So, while a java.sql.Date may show 2001-07-26, it's normalized only if the java.util.Date value is:
Thu Jul 26 00:00:00 EDT 2001
and while a java.sql.Time may show 14:01:00, it's normalized only if the java.util.Date value is:
Thu Jan 01 14:01:00 EST 1970
Answer :
Yes. Use ResultSet.getStatement(). From the resulting Statement you can use Statement.getConnection().
Question 75. What Is Pessimistic Concurrency?
Answer :
With a pessimistic approach, locks are used to ensure that no users, other than the one who holds the lock, can update data. It's generally explained that the term pessimistic is used because the expectation is that many users will try to update the same data, so one is pessimistic that an update will be able to complete properly. Locks may be acquired, depending on the DBMS vendor, automatically via the selected Isolation Level. Some vendors also implement 'Select... for Update', which explicitly acquires a lock.
Question 76. What Is Optimistic Concurrency?
Answer :
An optimistic approach dispenses with locks ( except during the actual update ) and usually involves comparison of timestamps, or generations of data to ensure that data hasn't changed between access and update times. It's generally explained that the term optimistic is used because the expectation is that a clash between multiple updates to the same data will seldom occur.
Question 77. When An Sql Select Statement Doesn't Return Any Rows, Is An Sqlexception Thrown?
Answer :
No. If you want to throw an exception, you could wrap your SQL related code in a custom class and throw something like ObjectNotFoundException when the returned ResultSet is empty.
Question 78. What Is Connection Pooling?
Answer :
Connection pooling is a technique used for sharing server resources among requesting clients. Connection pooling increases the performance of Web applications by reusing active database connections instead of creating a new connection with every request. Connection pool manager maintains a pool of open database connections.
Question 79. Which Java And Java.sql Data Types Map To My Specific Database Types?
Answer :
JDBC is, of necessity, reliant on the driver and underlying DBMS. These do not always adhere to standards as closely as we would like, including differing names for standard Java types. To deal with this, first, there are a number of tables available in the JDK JDBC documentation dealing with types.
Answer :
The answer should always be no. The two critical requirements are LAN/internet connectivity and an appropriate JDBC driver. Connectivity is usually via TCP/IP, but other communication protocols are possible. Unspoken, but assumed here is that the DBMS has been started to listen on a communications port. It is the JDBC driver's job to convert the SQL statements and JDBC calls to the DBMS' native protocol. From the server's point of view, it's just another data request coming into the port, the programming language used to send the data is irrelevant at that point.
Question 81. What Is A Jdbc 2.0 Datasource?
Answer :
The DataSource class was introduced in the JDBC 2.0 Optional Package as an easier, more generic means of obtaining a Connection. The actual driver providing services is defined to the DataSource outside the application ( Of course, a production quality app can and should provide this information outside the app anyway, usually with properties files or ResourceBundles ). The documentation expresses the view that DataSource will replace the common DriverManager method.
Question 82. What Types Of Datasource Objects Are Specified In The Optional Package?
Answer :
However, there are no standard methods available in the DataSource class to determine if one has obtained a pooled and/or distributed Connection.
Answer :
To answer the second question first, the tableIndexStatistic constant in the TYPE column will identify one of the rows in the ResultSet returned when DatabaseMetaData.getIndexInfo() is invoked. If you analyze the wordy API, a tableIndexStatistic row will contain the number of rows in the table in the CARDINALITY column and the number of pages used for the table in the PAGES column.
Answer :
DML is an abbreviation for Data Manipulation Language. This portion of the SQL standard is concerned with manipulating the data in a database as opposed to the structure of a database. The core verbs for DML are SELECT, INSERT, DELETE, UPDATE, COMMIT and ROLLBACK.
Question 85. Can I Use Jdbc To Execute Non-standard Features That My Dbms Provides?
Answer :
The answer is a qualified yes. As discussed under SQL Conformance: "One way the JDBC API deals with this problem is to allow any query string to be passed through to an underlying DBMS driver. This means that an application is free to use as much SQL functionality as desired, but it runs the risk of receiving an error on some DBMSs. In fact, an application query may be something other than SQL, or it may be a specialized derivative of SQL designed for specific DBMSs (for document or image queries, for example)."
Clearly this means either giving up portability or checking the DBMS currently used before invoking specific operations.
Question 86. How Can I Get Information About Foreign Keys Used In A Table?
Answer :
DatabaseMetaData.getImportedKeys() returns a ResultSet with data about foreign key columns, tables, sequence and update and delete rules.
Question 87. How Can I Determine Where A Given Table Is Referenced Via Foreign Keys?
Answer :
DatabaseMetaData.getExportedKeys() returns a ResultSet with data similar to that returned by Database MetaData .getImported Keys(), except that the information relates to other tables that reference the given table as a foreign key container.
Question 88. What Are The Considerations For Deciding On Transaction Boundaries?
Answer :
Transaction processing should always deal with more than one statement and a transaction is often described as a Logical Unit of Work ( LUW ). The rationale for transactions is that you want to know definitively that all or none of the LUW completed successfully. Note that this automatically gives you restart capability. Typically, there are two conditions under which you would want to use transactions:
Therefore, determining what completes the transaction or LUW should be the deciding factor for transaction boundaries.
Question 89. How Does One Get Column Names For Rows Returned In A Resultset?
Answer :
ResultSet rs = ...
...
ResultSetMetaData rsmd = rs.getMetaData();
int numCols = rsmd.getColumnCount();
for (int i = 1; i <= numCols; i++)
{
System.out.println("[" + i + "]" +
rsmd.getColumnName(i) + " {" +
rsmd.getColumnTypeName(i) + "}");
}
Question 90. Why Can't Tomcat Find My Oracle Jdbc Drivers In Classes111.zip?
Answer :
TOMCAT 4.0.1 on NT4 throws the following exception when I try to connect to Oracle DB from JSP.
javax.servlet.ServletException : oracle.jdbc.driver.OracleDriver
java.lang.ClassNotFoundException: oracle:jdbc:driver:OracleDriver
But, the Oracle JDBC driver ZIP file (classes111.zip)is available in the system classpath.
Copied the Oracle Driver class file (classes111.zip) in %TOMCAT_Home - Home%lib directory and renamed it to classess111.jar.
Able to connect to Oracle DB from TOMCAT 4.01 via Oracle JDBC-Thin Driver.
Answer :
// Use meta.getIndexInfo() will
//get you the PK index. Once
// you know the index, retrieve its column name
DatabaseMetaData meta = con.getMetaData();
String key_colname = null;
// get the primary key information
rset = meta.getIndexInfo(null,null, table_name, true,true);
while( rset.next())
{
String idx = rset.getString(6);
if( idx != null)
{
//Note: index "PrimaryKey" is Access DB specific
// other db server has diff. index syntax.
if( idx.equalsIgnoreCase("PrimaryKey"))
{
key_colname = rset.getString(9);
setPrimaryKey( key_colname );
}
}
}
Question 92. How Do I Insert/update Records With Some Of The Columns Having Null Value?
Answer :
Use either of the following PreparedStatement methods:
public void setNull(int parameterIndex, int sqlType) throws SQLException
public void setNull(int paramIndex, int sqlType, String typeName) throws SQLException
These methods assume that the columns are nullable. In this case, you can also just omit the columns in an INSERT statement; they will be automatically assigned null values.
Question 93. How Do I Disallow Null Values In A Table?
Answer :
Null capability is a column integrity constraint, normally applied at table creation time. Note that some databases won't allow the constraint to be applied after table creation. Most databases allow a default value for the column as well. The following SQL statement displays the NOT NULL constraint:
CREATE TABLE CoffeeTable (
Type VARCHAR(25) NOT NULL,
Pounds INTEGER NOT NULL,
Price NUMERIC(5, 2) NOT NULL
)
Answer :
DB2 Universal defaults to the 1.0 driver. You have to run a special program to enable the 2.0 driver and JDK support.
Question 95. Why Do I Get Unsatisfiedlinkerror When I Try To Use My Jdbc Driver?
Answer :
The first thing is to be sure that this does not occur when running non-JDBC apps. If so, there is a faulty JDK/JRE installation. If it happens only when using JDBC, then it's time to check the documentation that came with the driver or the driver/DBMS support. JDBC driver types 1 through 3 have some native code aspect and typically require some sort of client install. Along with the install, various environment variables and path or classpath settings must be in place. Because the requirements and installation procedures vary with the provider, there is no reasonable way to provide details here. A type 4 driver, on the other hand, is pure Java and should never exhibit this problem. The trade off is that a type 4 driver is usually slower.
Answer :
Use DatabaseMetaData.getMaxConnections() and compare to the number of connections currently open. Note that a return value of zero can mean unlimited or, unfortunately, unknown. Of course, driver Manager .getConnection () will throw an exception if a Connection can not be obtained.
Question 97. What Is The Jdbc Syntax For Using A Literal Or Variable In A Standard Statement?
Answer :
First, it should be pointed out that PreparedStatement handles many issues for the developer and normally should be preferred over a standard Statement.
Otherwise, the JDBC syntax is really the same as SQL syntax. One problem that often affects newbies ( and others ) is that SQL, like many languages, requires quotes around character ( read "String" for Java ) values to distinguish from numerics. So the clause:
"WHERE myCol = " + myVal
is perfectly valid and works for numerics, but will fail when myVal is a String. Instead use:
"WHERE myCol = '" + myVal + "'"
if myVal equals "stringValue", the clause works out to:
WHERE myCol = 'stringValue'
You can still encounter problems when quotes are embedded in the value, which, again, a PreparedStatement will handle for you.
Question 98. What Is An Sql Locator?
Answer :
A Locator is an SQL3 data type that acts as a logical pointer to data that resides on a database server. Read "logical pointer" here as an identifier the DBMS can use to locate and manipulate the data. A Locator allows some manipulation of the data on the server. While the JDBC specification does not directly address Locators, JDBC drivers typically use Locators under the covers to handle Array, Blob, and Clob data types.
Question 99. Why Do I Have To Reaccess The Database For Array, Blob, And Clob Data?
Answer :
Most DBMS vendors have implemented these types via the SQL3 Locator type
Some rationales for using Locators rather than directly returning the data can be seen most clearly with the Blob type. By definition, a Blob is an arbitrary set of binary data. It could be anything; the DBMS has no knowledge of what the data represents. Notice that this effectively demolishes data independence, because applications must now be aware of what the Blob data actually represents. Let's assume an employee table that includes employee images as Blobs.
Say we have an inquiry program that presents multiple employees with department and identification information. To see all of the data for a specific employee, including the image, the summary row is selected and another screen appears. It is only at this pont that the application needs the specific image. It would be very wasteful and time consuming to bring down an entire employee page of images when only a few would ever be selected in a given run.
Now assume a general interactive SQL application. A query is issued against the employee table. Because the image is a Blob, the application has no idea what to do with the data, so why bring it down, killing performance along the way, in a long running operation? Clearly this is not helpful in those applications that need the data everytime, but these and other considerations have made the most general sense to DBMS vendors.
Question 100. What Does It Mean To "materialize" Data?
Answer :
This term generally refers to Array, Blob and Clob data which is referred to in the database via SQL locators "Materializing" the data means to return the actual data pointed to by the Locator.
Question 101. How Can I Get Or Redirect The Log Used By Drivermanager And Jdbc Drivers?
Answer :
As of JDBC 2.0, use DriverManager.getLogWriter() and DriverManager.setLogWriter(PrintWriter out). Prior to JDBC 2.0, the DriverManager methods getLogStream() and setLogStream(PrintStream out) were used. These are now deprecated.
Question 102. How Can I Write To The Log Used By Drivermanager And Jdbc Drivers?
Answer :
The simplest method is to use DriverManager.println(String message), which will write to the current log.
Question 103. How Do I Receive A Resultset From A Stored Procedure?
Answer :
Stored procedures can return a result parameter, which can be a result set. For a discussion of standard JDBC syntax for dealing with result, IN, IN/OUT and OUT parameters, see Stored Procedures.
Answer :
I assume that your proxy is set to accept http requests only on port 80. If you want to have a local class behind the proxy connect to the database for you, then you need a servlet/JSP to receive an HTTP request and use the local class to connect to the database and send the response back to the client.
You could also use RMI where your remote computer class that connects to the database acts as a remote server that talks RMI with the clients. if you implement this, then you will need to tunnel RMI through HTTP which is not that hard.
In summary, either have a servlet/JSP take HTTP requests, instantiate a class that handles database connections and send HTTP response back to the client or have the local class deployed as RMI server and send requests to it using RMI.
Question 105. How Can I Determine The Isolation Levels Supported By My Dbms?
Answer :
Use DatabaseMetaData.supportsTransactionIsolationLevel(int level).
Answer :
The answer depends on both your code and the DBMS. If the program does not explicitly set the isolation level, the DBMS default is used. You can determine the default using Database MetaData. getDefault TransactionIsolation() and the level for the current Connection with Connection.getTransactionIsolation(). If the default is not appropriate for your transaction, change it with Connection.setTransactionIsolation(int level).
Answer :
In the SQL standard, CHAR is a fixed length data type. In many DBMSes ( but not all), that means that for a WHERE clause to match, every character must match, including size and trailing blanks. As Alessandro indicates, defining CHAR columns to be VARCHAR is the most general answer.
Question 108. Is Possible To Open A Connection To A Database With Exclusive Mode With Jdbc?
Answer :
I think you mean "lock a table in exclusive mode". You cannot open a connection with exclusive mode. Depending on your database engine, you can lock tables or rows in exclusive mode.
In Oracle you would create a statement st and run
st.execute("lock table mytable in exclusive mode");
Then when you are finished with the table, execute the commit to unlock the table. Mysql, Informix and SQLServer all have a slightly different syntax for this function, so you'll have to change it depending on your database. But they can all be done with execute().
Question 109. What Driver Should I Use For Scalable Oracle Jdbc Applications?
Answer :
Sun recommends using the thin ( type 4 ) driver.
Answer :
A solution that is perfectly portable to all databases, is to execute a query for checking if that unique value is present before inserting the row. The big advantage is that you can handle your error message in a very simple way, and the obvious downside is that you are going to use more time for inserting the record, but since you're working on a PK field, performance should not be so bad.
You can also get this information in a portable way, and potentially avoid another database access, by capturing SQLState messages. Some databases get more specific than others, but the general code portion is 23 - "Constraint Violations". UDB2, for example, gives a specific such as 23505, while others will only give 23000.
Answer :
Since the Connection interface ( and the underlying DBMS ) requires a specific user and password, there's not much of a way around this in a pool. While you could create a different Connection for each user, most of the rationale for a pool would then be gone. Debugging is only one of several issues that arise when using pools.
However, for debugging, at least a couple of other methods come to mind. One is to log executed statements and times, which should allow you to backtrack to the user. Another method that also maintains a trail of modifications is to include user and timestamp as standard columns in your tables. In this last case, you would collect a separate user value in your program.
Answer :
"It can be implemented in a wide variety of ways..." and is pretty vague about what can actually be done. In general, readData() would obtain or create the data to be loaded, then use CachedRowSet methods to do the actual loading. This would usually mean inserting rows, so the code would move to the insert row, set the column data and insert rows. Then the cursor must be set to to the appropriate position.
Question 113. How Does A Custom Rowsetreader Get Called From A Cachedrowset?
Answer :
The Reader must be registered with the CachedRowSet using Cached RowSet .setReader javax.sql. RowSet Reader reader). Once that is done, a call to Cached RowSet. execute() will, among other things, invoke the readData method.
Question 114. How Can I Create A Custom Rowsetmetadata Object From Scratch?
Answer :
One unfortunate aspect of RowSetMetaData for custom versions is that it is an interface. This means that implementations almost have to be proprietary. The JDBC RowSet package is the most commonly available and offers the sun.jdbc.rowset .RowSetMetaDataImpl class. After instantiation, any of the RowSetMetaData setter methods may be used. The bare minimum needed for a RowSet to function is to set the Column Count for a row and the Column Types for each column in the row. For a working code example that includes a custom RowSet MetaData.
Question 115. Where Can I Find Info, Frameworks And Example Source For Writing A Jdbc Driver?
Answer :
There a several drivers with source available, like MM.MySQL, SimpleText Database, FreeTDS, and RmiJdbc. There is at least one free framework, the jxDBCon-Open Source JDBC driver framework. Any driver writer should also review For Driver Writers.
Answer :
You still need to get and install a JDBC technology-enabled driver that supports the database that you are using. There are many drivers available from a variety of sources. You can also try using the JDBC-ODBC Bridge if you have ODBC connectivity set up already. The Bridge comes with the Java 2 SDK, Standard Edition, and Enterprise Edition, and it doesn't require any extra setup itself. The Bridge is a normal ODBC client. Note, however, that you should use the JDBC-ODBC Bridge only for experimental prototyping or when you have no other driver available.
Question 117. If I Use The Jdbc Api, Do I Have To Use Odbc Underneath?
Answer :
No, this is just one of many possible solutions. We recommend using a pure Java JDBC technology-enabled driver, type 3 or 4, in order to get all of the benefits of the Java programming language and the JDBC API.
Answer :
The JDBC-ODBC Bridge is bundled with the Java 2 SDK, Standard Edition, so there is no need to download it separately.
Answer :
No, but it is easy to find the number of rows. If you are using a scrollable result set, rs, you can call the methods rs.last and then rs.getRow to find out how many rows rs has. If the result is not scrollable, you can either count the rows by iterating through the result set or get the number of rows by submitting a query with a COUNT column in the SELECT clause.
Question 120. What Is The Query Used To Display All Tables Names In Sql Server (query Analyzer)?
Answer :
select * from information_schema.tables.
Answer :
Creating and garbage collecting potentially large numbers of objects (millions) unnecessarily can really hurt performance. It may be better to provide a way to retrieve data like strings using the JDBC API without always allocating a new object. We are studying this issue to see if it is an area in which the JDBC API should be improved.
Answer :
You are probably using a driver implemented for the JDBC 1.0 API. You need to upgrade to a JDBC 2.0 driver that implements scrollable result sets. Also be sure that your code has created scrollable result sets and that the DBMS you are using supports them.
Question 123. Is The Jdbc-odbc Bridge Multi-threaded?
Answer :
No. The JDBC-ODBC Bridge does not support concurrent access from different threads. The JDBC-ODBC Bridge uses synchronized methods to serialize all of the calls that it makes to ODBC. Multi-threaded Java programs may use the Bridge, but they won't get the advantages of multi-threading. In addition, deadlocks can occur between locks held in the database and the semaphore used by the Bridge. We are thinking about removing the synchronized methods in the future. They were added originally to make things simple for folks writing Java programs that use a single-threaded ODBC driver.
Answer :
No. There aren't any JDBC technology-enabled drivers bundled with the JDK 1.1.x or Java 2 Platform releases other than the JDBC-ODBC Bridge. So, developers need to get a driver and install it before they can connect to a database. We are considering bundling JDBC technology- enabled drivers in the future.
Question 125. How To Use Jdbc To Connect Microsoft Access?
Answer :
There is a specific tutorial at javacamp.org. Check it out.
Question 126. What Are The Common Tasks Of Jdbc?
Answer :
Create an instance of a JDBC driver or load JDBC drivers through jdbc.drivers
Answer :
The ResultSet.getXXX methods are the only way to retrieve data from a ResultSet object, which means that you have to make a method call for each column of a row. It is unlikely that this is the cause of a performance problem, however, because it is difficult to see how a column could be fetched without at least the cost of a function call in any scenario. We welcome input from developers on this issue.
Answer :
Most desktop databases currently require a JDBC solution that uses ODBC underneath. This is because the vendors of these database products haven't implemented all-Java JDBC drivers.
The best approach is to use a commercial JDBC driver that supports ODBC and the database you want to use. See the JDBC drivers page for a list of available JDBC drivers. The JDBC-ODBC bridge from Sun's Java Software does not provide network access to desktop databases by itself.
The JDBC-ODBC bridge loads ODBC as a local DLL, and typical ODBC drivers for desktop databases like Access aren't networked. The JDBC-ODBC bridge can be used together with the RMI-JDBC bridge, however, to access a desktop database like Access over the net. This RMI-JDBC-ODBC solution is free.
Question 129. How To Insert And Delete A Row Programmatically? (new Feature In Jdbc 2.0)
Answer :
Make sure the resultset is updatable.
1. move the cursor to the specific position.
uprs.moveToCurrentRow();
2. set value for each column.
uprs.moveToInsertRow();//to set up for insert
uprs.updateString("col1" "strvalue");
uprs.updateInt("col2", 5);
...
3. call inserRow() method to finish the row insert process.
uprs.insertRow();
To delete a row: move to the specific position and call deleteRow() method:
uprs.absolute(5);
uprs.deleteRow();//delete row 5
To see the changes call refreshRow();
uprs.refreshRow();
Answer :
Question 131. What Is A Data Source
Answer :
A DataSource class brings another level of abstraction than directly using a connection object. Data source can be referenced by JNDI. Data Source may point to RDBMS, file System , any DBMS etc.
Question 132. What Is Metadata
Answer :
It is information about one of two things: Database information (java.sql.DatabaseMetaData), or Information about a specific ResultSet (java.sql.ResultSetMetaData). Use DatabaseMetaData to find information about your database, such as its capabilities and structure. Use ResultSetMetaData to find information about the results of an SQL query, such as size and types of columns.
Question 133. How Do You Insert Images In Database Using Jdbc?
Answer :
We can store images in the databse using the BLOB datatype where in the image is stored as a byte stream.
Question 134. How Many Statements Can We Create With One Connection?
Answer :
There is no such limit on number of statements to be created.
Question 135. What Do We Use Setautocommit() For?
Answer :
The DML operations by default are committed. If we wish to avoid the commit by default, setAutoCommit(false) has to be called on the Connection object.
Once the statements are executed, commit() has to be called on the Connection object explicitly.
Question 136. What Packages Are Being Used By Jdbc?
Answer :
Following packages are used in JDBC
Question 137. How Do You Call A Stored Procedure From Java?
Answer :
You can call a stored procedure using Callable statements CallableStatement cs = con.prepareCall("{call StoredProc}"); ResultSet rs = cs.executeQuery();
Question 138. Why Do We Need Batch Updates?
Answer :
Let's say there are 100 records need to be insert. If we execute normal statemets the no of transactions will be 100 (in terms of connection making to DB). using batch updates we can add 100 rec to batch and the no of transactions will be only one in this case. This will reduce the burdon on db, which is very costly in terms of resources.
Question 139. What Do You Mean By Batch Updates?
Answer :
If you want to execute a set of statements, i.e. SQL statements at a time then we use batch update statement.
resultset=pst.batchUpdate();
Question 140. What Are The Tasks Of Jdbc?
Answer :
Following are the tasks of JDBC
Question 141. What Is A Stored Procedure?
Answer :
A stored procedure is a group of SQL statements that form a logical unit and perform a particular task. Stored procedures are used to encapsulate a set of operations or queries to execute on a database server. For example, operations on an employee database (hire, fire, promote, lookup) could be coded as stored procedures executed by application code. Stored procedures can be compiled and executed with different parameters and results, and they may have any combination of input, output, and input/output parameters.
Question 142. How Do You Create Jdbc Statements?
Answer :
Connection con = null;
Statement st = null;
// Obtain connection here
st = con.createStatement();
ResultSet rs = null;
rs = st.executeQuery("SELECT * FROM users");
int recordsUpdated;
recordsUpdated = st.executeUpdate("DELETE FROM users WHERE user_id = 1");
Question 143. When Do We Used Prepared Statements?
Answer :
If you want to execute a Statement object many times, it will normally reduce execution time to use a PreparedStatement object instead.
The main feature of a PreparedStatement object is that, unlike a Statement object, it is given an SQL statement when it is created. 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.
Although PreparedStatement objects can be used for SQL statements with no parameters, you will probably use them most often for SQL statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same statement and supply it with different values each time you execute it. You will see an example of this in the following sections.
Question 144. What Are Different Types Of Statements In Jdbc?
Answer :
java.sql.Statement - Top most interface which provides basic methods useful for executing SELECT, INSERT, UPDATE and DELETE SQL statements.
java.sql.PreparedStatement - An enhanced verion of java.sql.Statement which allows precompiled queries with parameters. It is more efficient to use java.sql.PreparedStatement if you have to specify parameters to your SQL queries.
java.sql.CallableStatement - Allows you to execute stored procedures within a RDBMS which supports stored procedures (MySQL doesn't support stored procedures at the moment).
Question 145. How Do You Establish A Connection?
Answer :
Loading Drivers
Class.forName("Driver");
Getting connection
Connection con = DriverManager.getConnection(url, "myLogin", "myPassword");
Question 146. How Do You Load The Drivers?
Answer :
Class.forName() method is used in JDBC to load the JDBC drivers dynamically.
Question 147. What Are The Components Of Jdbc
Answer :
JDBC Components-
Answer :
Short for Java Database Connectivity, a Java API that enables Java programs to execute SQL statements. This allows Java programs to interact with any SQL-compliant database. Since nearly all relational database management systems (DBMSs) support SQL, and because Java itself runs on most platforms, JDBC makes it possible to write a single database application that can run on different platforms and interact with different DBMSs.
JDBC is similar to ODBC, but is designed specifically for Java programs, whereas ODBC is language-independent.
Question 149. What's The Difference Between Type_scroll_insensitive , And Type_scroll_sensitive
Answer :
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 NAME, SALARY FROM PERSON"); srs.afterLast();
while (srs.previous())
{
String name = srs.getString("NAME");
float salary = srs.getFloat("SALARY");
System.out.println(name + " " + salary);
}
Answer :
Answer :
Question 152. Explain The Concepts Of Tomcat Servlet Container?
Answer :
Question 153. How Do You Create Multiple Virtual Hosts?
Answer :
If you want tomcat to accept requests for different hosts e.g., www.myhostname.com then you must
0. create ${catalina.home}/www/appBase , ${catalina.home}/www/deploy, and ${catalina.home} /conf /Catalina/www.myhostname.com
1. add a host entry in the server.xml file
<Host appBase="www/appBase" name="www.myhostname.com"/>
2. Create the the following file under conf/Catalina/www.myhostname.com/ROOT.xml
<?xml version="1.0" encoding="UTF-8"?>
<Context
path="/"
docBase="www/deploy/mywebapp.war"
reloadable="true" antiJARLocking="true">
</Context>
Add any parameters specific to this hosts webapp to this context file
3. put your war file in ${catalina.home}/www/deploy
When tomcat starts, it finds the host entry, then looks for any context files and will start any apps with a context.
Question 154. How Will You Load Properties File?
Answer :
// Assuming you are in a Servlet extending HttpServlet
// This will look for a file called "/more/cowbell.properties" relative
// to your servlet Root Context
InputStream is = getServletContext().getResourceAsStream("/more/cowbell.properties");
Properties p = new Properties();
p.load(is);
is.close();
Question 155. Can I Set Java System Properties Differently For Each Webapp?
Answer :
No. If you can edit Tomcat's startup scripts, you can add "-D" options to Java. But there is no way to add such properties in web.xml or the webapp's context.
Question 156. How Do I Configure Tomcat To Work With Iis And Ntlm?
Answer :
Follow the standard instructions for when the isapi_redirector.dll
Configure IIS to use "integrated windows security".
In server.xml, make sure you disable tomcat authentication.
Question 157. How Do I Override The Default Home Page Loaded By Tomcat?
Answer :
After successfully installing Tomcat, you usually test it by loading http://localhost:8080 . The contents of that page are compiled into the index_jsp servlet. The page even warns against modifying the index.jsp files for this reason. Luckily, it is quite easy to override that page. Inside $TOMCAT_HOME/conf/web.xml there is a section called <welcome-file-list> and it looks like this:
<welcome-file-list>
<welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
The default servlet attempts to load the index.* files in the order listed. You may easily override the index.jsp file by creating an index.html file at $TOMCAT_HOME/webapps/ROOT. It's somewhat common for that file to contain a new static home page or a redirect to a servlet's main page. A redirect would look like:
<html>
<head>
<meta http-equiv="refresh" content="0;URL=http://mydomain.com/some/path/to/servlet/homepage/">
</head>
<body>
</body>
</html>
This change takes effect immediately and does not require a restart of Tomcat.
Question 158. How Do I Enable Server Side Includes (ssi)?
Answer :
Two things have to be done for tomcat to aknowledge SSI scripts:
1. Rename $CATALINA_BASE/server/lib/servlets-ssi.renametojar to $CATALINA_BASE/server/lib/servlets-ssi.jar.
2. Uncomment the section of web.xml found in $CATALINA_BASE/conf/web.xml that deals with SSI. it looks like this when it is uncommented:
<servlet>
<servlet-name>ssi</servlet-name>
<servlet-class>
org.apache.catalina.ssi.SSIServlet
</servlet-class>
<init-param>
<param-name>buffered</param-name>
<param-value>1</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>expires</param-name>
<param-value>666</param-value>
</init-param>
<init-param>
<param-name>isVirtualWebappRelative</param-name>
<param-value>0</param-value>
</init-param>
<load-on-startup>4</load-on-startup>
</servlet>
Question 159. What Is Servlet?
Answer :
A servlet is a Java technology-based Web component, managed by a container called servlet container or servlet engine, that generates dynamic content and interacts with web clients via a request\/response paradigm.
Question 160. Why Is Servlet So Popular?
Answer :
Because servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.
Question 161. What Is Servlet Container?
Answer :
The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle.
Answer :
The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response.
Question 163. If A Servlet Is Not Properly Initialized, What Exception May Be Thrown?
Answer :
During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException.
Question 164. Given The Request Path Below, Which Are Context Path, Servlet Path And Path Info?
Answer :
/bookstore/education/index.html
context path: /bookstore
servlet path: /education
path info: /index.html
Question 165. What Is Filter? Can Filter Be Used As Request Or Response?
Answer :
A filter is a reusable piece of code that can transform the content of HTTP requests,responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource.
Question 166. When Using Servlets To Build The Html, You Build A Doctype Line, Why Do You Do That?
Answer :
I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE line tells HTML validators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors.
Question 167. What Is New In Servletrequest Interface ? (servlet 2.4)
Answer :
The following methods have been added to ServletRequest 2.4 version:
public int getRemotePort()
public java.lang.String getLocalName()
public java.lang.String getLocalAddr()
public int getLocalPort()
Question 168. Request Parameter How To Find Whether A Parameter Exists In The Request Object?
Answer :
Question 169. How Can I Send User Authentication Information While Making Url Connection?
Answer :
You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.
Question 170. Can We Use The Constructor, Instead Of Init(), To Initialize Servlet?
Answer :
Yes , of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't. The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won't have access to a ServletConfig or Servlet Context.
Question 171. How Can A Servlet Refresh Automatically If Some New Data Has Entered The Database?
Answer :
You can use a client-side Refresh or Server Push.
Question 172. The Code In A Finally Clause Will Never Fail To Execute, Right?
Answer :
Using System.exit(1); in try block will not allow finally code to execute.
Question 173. What Mechanisms Are Used By A Servlet Container To Maintain Session Information?
Answer :
Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information.
Question 174. Difference Between Get And Post ?
Answer :
In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 260 characters, not secure, faster, quick and easy.
In POST Your name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the form's output. It is used to send a chunk of data to the server to be processed, more versatile, most secure.
Question 175. What Is Session?
Answer :
The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests.
Question 176. What Is Servlet Mapping?
Answer :
The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets.
Question 177. What Is Servlet Context ?
Answer :
The servlet context is an object that contains a servlet's view of the Web application within which the servlet is running. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use.
Question 178. Which Interface Must Be Implemented By All Servlets?
Answer :
Servlet interface.
Question 179. Explain The Life Cycle Of Servlet?
Answer :
Loaded(by the container for first request or on start up if config file suggests load-on-startup), initialized( using init()), service(service() or doGet() or doPost()..), destroy(destroy()) and unloaded.
Answer :
An instance of servlet is created when the servlet is loaded for the first time in the container. Init() method is used to configure this servlet instance. This method is called only once in the life time of a servlet, hence it makes sense to write all those configuration details about a servlet which are required for the whole life of a servlet in this method.
Question 181. Why Don't We Write A Constructor In A Servlet?
Answer :
Container writes a no argument constructor for our servlet.
Answer :
Container creates instance of servlet by calling Class.forName(className).newInstance().
Answer :
Yes, but Before calling the destroy() method, the servlet container waits for the remaining threads that are executing the servlet’s service() method to finish.
Answer :
We can give relative URL when we use ServletRequest and not while using ServletContext.
Answer :
Since ServletRequest has the current request path to evaluae the relative path while ServletContext does not.
Question 186. Explain The Life Cycle Methods Of A Servlet?
Answer :
The javax.servlet.Servlet interface defines the three methods known as life-cycle method.
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
First the servlet is constructed, then initialized wih the init() method.Any request from client are handled initially by the service() method before delegating to thedoXxx() methods in the case of HttpServlet.
The servlet is removed from service, destroyed with the destroy() methid, then garbaged collected and finalized.
Answer :
The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter the path to the resource to be included or forwarded to, which can be relative to the request of the calling servlet. If the path begins with a "/" it is interpreted as relative to the current context root.
The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accepts relative paths. All path must sart with a "/" and are interpreted as relative to curent context root.
Question 188. Explain The Directory Structure Of A Web Application?
Answer :
The directory structure of a web application consists of two parts.
WEB-INF folder consists of
Question 189. What Are The Common Mechanisms Used For Session Tracking?
Answer :
Question 190. Explain Servletcontext?
Answer :
ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web applicationor servlet container's version. Every web application has one and only one ServletContext and is accessible to all active resource of that application.
Question 191. What Is Preinitialization Of A Servlet?
Answer :
A container doesnot initialize the servlets ass soon as it starts up, it initializes a servlet when it receives a request for that servlet first time. This is called lazy loading. The servlet specification defines the
Question 192. What Is The Difference Between Difference Between Doget() And Dopost()?
Answer :
A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation.
doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string.
Question 193. What Is The Difference Between Httpservlet And Genericservlet?
Answer :
A GenericServlet has a service() method aimed to handle requests. HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract.
Question 194. What Is The Difference Between Servletcontext And Servletconfig?
Answer :
ServletContext: Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.
ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet.
Question 195. What Are The Type Of Protocols Supported By Httpservlet?
Answer :
It extends the GenericServlet base class and provides an framework for handling the HTTP protocol. So, HttpServlet only supports HTTP and HTTPS protocol.
Question 196. What Are The Directory Structure Of Web Application?
Answer :
Web component follows the standard directory structure defined in the J2EE specification.
Directory Structure of Web Component
/ index.htm, JSP, Images etc..
Web-inf
web.xml
classes
servlet classes
lib
jar files
Question 197. What Is Servletcontext?
Answer :
ServletContext is an Interface that defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.)
Question 198. What Do You Understand By Servlet Mapping?
Answer :
Servlet mapping defines an association between a URL pattern and a servlet. You can use one servlet to process a number of url pattern (request pattern). For example in case of Struts *.do url patterns are processed by Struts Controller Servlet.
Question 199. What Must Be Implemented By All Servlets?
Answer :
The Servlet Interface must be implemented by all servlets.
Question 200. What Are The Differences Between Servlet And Applet?
Answer :
Servlets are server side components that runs on the Servlet container. Applets are client side components and runs on the web browsers. Servlets have no GUI interface.
Question 201. What Are The Uses Of Servlets?
Answer :
Question 202. What Are The Objects That Are Received When A Servlets Accepts Call From Client?
Answer :
The objects are ServeltRequest and ServletResponse . The ServeltRequest encapsulates thecommunication from the client to the server. While ServletResponse encapsulates the communication from the Servlet back to the client.
Question 203. What Is Servlets And Explain The Advantages Of Servlet Life Cycle?
Answer :
Servlets are modules that run within the server and receive and respond to the requests made by the client. Servlets retrieve most of the parameters using the input stream and send their responses using an output stream.
Servlets are used to extend the server side functionality of a website. They communicate with various application on the server side and respond to the request made by the client.
Question 204. What Are The General Advantages And Selling Points Of Servlets?
Answer :
Servlets exhibit the following characteristics:
Question 205. Whats The Advantages Using Servlets Over Using Cgi?
Answer :
CGI programs run outside the webserver. So a new process must be started to execute a CGI program. CGI programs are designed to handle a single request at a time. After that they return the result to the web server and exit.
On the other hand servlets can handle multiple requests concurrently. They run within web servers. They generate dynamic content that is easier to write and faster to run.
Question 206. What Are Different Authentication Options Available In Servlets?
Answer :
There are four ways of Authentication options available in servlets
HTTP basic authentication
In this, server uses the username and password provided by the client and these credentials are transmitted using simple base64 encoding.
HTTP digest authentication
This option is same the basic authentication except the password is encrypted and transmitted using SHA or MD5.
HTTPS client authentication
This options is based on HTTP over SSL.
Form-based authentication
Form-based authentication uses login page to collect username and password.
Question 207. Explain Why Httpservlet Is Declared Abstract.
Answer :
The Constructor HttpServlet() does nothing because this is an abstract class. Default implementations in a few Java classes like HttpServlet don’t really do anything. Hence, they need to be overridden.
Usually one of the following methods of HttpServlet must be overridden by a subclass:
doGet, if the servlet supports HTTP GET requests
doPost, HTTP POST requests
doPut, HTTP PUT requests
doDelete, HTTP DELETE requests
init and destroy, to manage resources
getServletInfo, to provide information
However, there doesn’t seem to be any reason why the service method should be overridden because it eventually dispatches the task to one of the doXXX methods.
Question 208. What Is The Genericservlet Class?
Answer :
GenericServlet makes writing servlets easier. To write a generic servlet, all you need to do is to override the abstract service method.
Question 209. Is Possible To Have A Constructor For A Servlet?
Answer :
Yes, it is possible to have a constructor for a servlet. However, it is not practiced usually. The operations with the constructor can be performed as usual just that it cannot be called explicitly using the ‘new’ keyword. This is implicitly handled by the servlet container. Thus, the container performs initialization as well as constructor functions.
Question 210. What Is The Difference Between An Applet And A Servlet?
Answer :
Applets
Servlets
Question 211. Define Http Tunneling?
Answer :
In some organizations, the intranet is blocked by a firewall to the internet. It is exposed to the outer networks only by means of webserver port that accept only Http requests. In such situations, if protocols other than http are used, then they get rejected. The solution is to have them encapsulated in http or https and sent as an HttpRequest. Thus, masking other protocols as http requests is called HTTP Tunneling.
Question 212. List Out The Difference Between Servletconfig And Servletcontext?
Answer :
Both are interfaces in the package javax.servlet.
Question 213. What Is The Difference Between Using Getsession(true) And Getsession(false) Methods?
Answer :
getSession(true) will check whether a session already exists for the user. If yes, it will return that session object else it will create a new session object and return it.
getSession(false) will check existence of session. If session exists, then it returns the reference of that session object, if not, this methods will return null.
Question 214. List Out Difference Between A Javabean From A Servlet?
Answer :
Servlets are Java based analog to CGI programs, implemented by means of a servlet container associated with an HTTP server. Servlets run on the server side. Beans are reusable code components written in Java that one can use in a variety of programming environments. JavaBeans are to Java what ActiveX controls are to Microsoft. Javabeans can run on server side, client side, within an applet etc.
So, both have nothing in common except Java.
Answer :
RMI (Remote Method Invocation) are a means of client server communication. In this, the client invokes a method on the server machine and the server machine process returns the result back to the client. We need to run RMI registry to use RMI.
Servlets are used to extend the server side functionality of a website. They communicate with various application on the server side and respond to the request made by the client. Servlets are modules that run within the server and receive and respond to the requests made by the client. Servlets retrieve most of the parameters using the input stream and send their responses using an output stream.
Question 216. What Is Cdma One ?
Answer :
Also know as IS-95, CDMA One is a 2nd generation wireless technology. Supports speeds from 14.4Kbps to 115K bps.
Question 217. What Is Project Glassfish?
Answer :
GlassFish is the name for the open source development project for building a Java EE 5 application server. It is based on the source code for Sun Java System Application Server PE 9 donated by Sun Microsystems and TopLink persistence code donated by Oracle. This project provides a structured process for developing a high quality application server that makes new features available faster than ever before. It is the response to Java developers who want access to the source code and the ability to contribute to the development of Sun’s next generation application server which is based on GlassFish. This project is designed to encourage communication between Sun and Oracle engineers and the community and will enable all developers to participate in the application server development process.
Question 218. What Is Available On The Website?
Answer :
Nightly builds and the source code for the application server are available. As with other community development sites, you will also find email lists, discussion forums, news, feedback, licensing information, and extensive help resources.
Question 219. How Large Is The Glassfish Community?
Answer :
The GlassFish development community is just getting started so it is small but rapidly growing. There are over 100 contributors already signed up. The number of Sun and Oracle engineers working on this product is comparable in size to other application server developer communities today. With the release of project GlassFish to the community, we expect to greatly increase the number of developers working on the code.
Question 220. Can I As A Developer Make Any Changes I Want To The Code?
Answer :
Yes, developers have free access to the source code under the terms of the Common Development and Distribution License (CDDL) v1.0 and are free to change it as they see fit. To be able to claim Java Compatibility, developers of commercial distributions will need to sign the Java Developer License (JDL) and verify the code passes the compatibility test suite (CTS) before they can redistribute it. Anyone can sign a contribution agreement and work on the code to contribute changes, bug fixes, and features.
Question 221. How Often Can I Get An Update Of Glassfish?
Answer :
Updated builds for GlassFish will be posted every night to glassfish.dev.java.net. These code pushes have gone through very basic testing to ensure they will build and execute but have not been tested as thoroughly as our production releases. Additionally, you have read access to the same CVS tree that the developers do – so you always see the latest versions of the code there. Occasionally, typically weekly or so, we will push a “promoted” build which has been more thoroughly tested and will contain many more documented features than the regular nightly builds. A supported Beta and FCS version of the Sun Java System Application Server 9.0 which is built on GlassFish.
Question 222. What Version Of Java Ee Does This Apply To?
Answer :
GlassFish will implement the latest version of the Java EE platform, Java EE 5, and the two should become final at around the same time. At that time Sun will also release a final, supported and compatible Sun Java System Application Server PE 9.0 based on GlassFish.
Question 223. What Is Being Released And When?
Answer :
In June of 2005, Sun published project GlassFish by making the web site available to the public. Developers can access source code, nightly builds, discussion groups, and mailing lists. This is the first time developers were able to see and participate in the Application Server development process. Over the next 6 months, Sun will gradually roll out more information and more details about the code. Initially, access will be provided to the web-tier followed by other modules as GlassFish is developed.
Question 224. How Does This Impact Java Ee Licensees?
Answer :
Project GlassFish opens up Java EE to a larger audience that will ultimately be the customers of the Java EE licensees. GlassFish does not change any of the license terms for licensees. Under their license terms, licensees can still sell or distribute code and use the Java Compatibility brand for products which have passed the TCK. Under the license terms of the CDDL, which is granted to developers, they can use, edit, and alter the code, and distribute it or use it in production. However they do not have a license to use the CTS nor can they use the Java Compatibility brand.
Question 225. What Are The Licensing Terms?
Answer :
The OSI-approved CDDL license is being used for project GlassFish which allows developers to view, use, edit, and alter the code, and distribute it or use it in production. Portions of this code are not yet available in source form. Because of this, a few portions are currently also under a Binary Distribution License. As time goes on, we’ll make more of the code available, with the eventual goal of making all the code available, and removing the Binary Distribution license. This isn’t some sort of evil plot – it’s hard work moving stuff out into an Open environment, we expect to have a roadmap for our timing for this published by the end of the Summer.
People who want to redistribute a build of our application server do not have a license to use the CTS nor can they use the Java Compatibility brand. They may choose to sign a JDL commercial license and pass the CTS which would then allow them to distribute the code and use the Java Compatibility brand.
Question 226. I Am A Current Scsl Licensee, And Want To Use The Cddl. Can I Do This?
Answer :
Yes. Current SCSL licensees can choose to use the CDDL, but they must click through the new license, and use the CDDL notification in their work.
Question 227. How To Call A Stored Procedure From Jdbc?
Answer :
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.
E.g.
CallableStatement cs = con.prepareCall("{call SHOW_SUPPLIERS}");
Question 228. What Class.forname Will Do While Loading Drivers?
Answer :
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.
Question 229. What Is Relational Database?
Answer :
Either as a programmer or a user, you have probably interacted with a database before. A database is simply a program that makes it easy to store and retrieve data. The data can be numeric, string or more complex objects, such as a video database. A relational database is one implementation of a database—one that organizes data in tables.
A table is made up of rows and columns. In relational database terminology, the table is called a file, a row is called a record and a column is called afield. One of the features of a relational database is that you can retrieve the data by its content. For example, assume you have a relational database with a table made up of two fields, one for names and another for phone numbers. To retrieve data by content means that you can simply ask the database to retrieve a phone number for a particular name. You do not have to specify an explicit row and column to get a data element.
Question 230. Explain The Sql?
Answer :
SQL (Structured Query Language) is a high-level language that hides particular relational database's implementation. SQL provides a standard database interface. Using SQL, your program is not stuck with one particular vendor's database management system (DBMS). Ideally, you can change from one DBMS to another without changing your application. In reality, however, each vendor's interpretation of SQL is slightly different, so switching from one DBMS to another normally requires some work.
SQL is officially pronounced "ess-cue-ell," but most people call it "sequel." You use SQL to interact with relational databases. There are three main operations that you may want to perform with a database: database manipulation, definition, and administration. We shall focus on database manipulation, that is, data retrieval and modification. The other operations database definition and administration, correspond to database creation and management, which most users are not in a position to perform.
Question 231. How Applet Restrictions Affect Jdbc? Explain.
Answer :
As you have learned, a Java applet can only connect to the server from which the user downloaded the applet. In addition, some browser, such as Netscape, do not let an applet write or read local files. Therefore, a database applet cannot write search result to a file or insert data into a database. You must take these restrictions into consideration when you design an applet that is going to access a database.
Question 232. How To Set A Parameter To Null?
Answer :
As you have learned within a database, the null value is a valid field value. Sometimes, depending on your database contents, you will want to set a parameter within a prepare statement to null There are two ways that you can do this. First, you can pass null as an argument to any of the setx methods. The JDBC, in turn, will set the data field to null. Second, you can call the setNull method.
Question 233. What Is The Java.sql.timestamp Class?
Answer :
Within a Java database, you can use the TIMESTAMP type to store a time with a resolution in nanoseconds. Java's Date class, on the other hand, only measures to milliseconds. Therefore, the JDBC developers have made a java.sql.Timestamp class. This new Timestamp class extends the java.util. Date class by adding a nanosecond variable to store the time-stamp information.
Question 234. How To Serialize Objects With Multiple References?
Answer :
When you serialize objects that your program references multiple times, you should write the object only one time. To do this, you can use a hashtable to keep track of the object that you have written. When you write an object for the first time, you add its reference to the hashtable along with a unique ID value. The ID can be any numeric value. You write the object's class name and ID value to the stream, followed by the object itself. If your program encounters the object a second time, you only write the name of the object and ID value to the stream.
Question 235. How To Deserialize Objects With Multiple References?
Answer :
When you deserialize objects that you have referenced multiple times, you should reconstruct the objects only once. You should use a hashtable to keep track of objects that you must reconstruct. When you read an object for the first time, you add the reference to the hashtable along with the object's ID value. If you encounter the object a second time, you use the reference that is stored in the hashtable.
Question 236. What Is Stored Procedure?
Answer :
Stored procedure is a group of SQL statements that forms a logical unit and performs a particular task. Stored Procedures are used to encapsulate a set of operations or queries to execute on database. Stored procedures can be compiled and executed with different parameters and results and may have any combination of input/output parameters.
Question 237. What Does A Thread Enter When It Terminates Its Processing?
Answer :
When a thread terminates its processing, it enters the dead state.
Question 238. What Is Servlet Chaining?
Answer :
Servlet chaining is a technique in which two or more servlets can cooperate in servicing a single request. In servlet chaining, one servlet's output is piped to the next servlet's input. This process continues until the last servlet is reached. Its output is then sent back to the client.
Question 239. What Is Inet Address?
Answer :
Every computer connected to a network has an IP address. An IP address is a number that uniquely identifies each computer on the Net. An IP address is a 32-bit number.
Question 240. What Is Unicastremoteobject?
Answer :
All remote objects must extend UnicastRemoteObject, which provides functionality that is needed to make objects available from remote machines.
JDBC Related Tutorials |
|
---|---|
Core Java Tutorial | JSP Tutorial |
Java Servlets Tutorial | EJB(Enterprise JavaBeans) Tutorial |
Java Bean Utils Tutorial | AWT (Abstract Window Toolkit) Tutorial |
All rights reserved © 2020 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.