Interview Questions.

Top 100+ Jdbc Interview Questions And Answers


Top 100+ Jdbc Interview Questions And Answers

Question 1. What Is The Jdbc?

Answer :

Java Database Connectivity (JDBC) is a widespread Java API to interact with relational databases form Java. JDBC has set of training and interfaces which can use from Java application and speak to database with out getting to know RDBMS info and using Database Specific JDBC Drivers.

Question 2. What Are The New Features Added To Jdbc 4.Zero?

Answer :

The main functions added in JDBC four.0 include :

Auto-loading of JDBC driver class
Connection management upgrades
Support for RowId SQL type
DataSet implementation of SQL using Annotations
SQL exception managing improvements
SQL XML support
Core Java Interview Questions
Question three. Explain Basic Steps In Writing A Java Program Using Jdbc?

Answer :

JDBC makes the interplay with RDBMS simple and intuitive. When a Java software wishes to access database :

Load the RDBMS particular JDBC driving force due to the fact this driver in reality communicates with the database (Incase of JDBC 4.0 this is routinely loaded).
Open the connection to database that's then used to send SQL statements and get outcomes returned.
Create JDBC Statement object. This object incorporates SQL query.
Execute statement which returns resultset(s). ResultSet consists of the tuples of database desk as a result of SQL query.
Process the end result set.
Close the connection.
Question 4. What Are The Main Components Of Jdbc ?

Answer :

The lifestyles cycle of a servlet consists of the following levels:

DriverManager: Manages a listing of database drivers. Matches connection requests from the java application with the right database motive force the use of verbal exchange subprotocol. The first driver that recognizes a certain subprotocol beneath JDBC will be used to set up a database Connection.
Driver: The database communications link, managing all verbal exchange with the database. Normally, as soon as the driving force is loaded, the developer want not name it explicitly.
Connection : Interface with all methods for contacting a database.The connection object represents communique context, i.E., all verbal exchange with database is thru connection item best.
Statement : Encapsulates an SQL declaration that's surpassed to the database to be parsed, compiled, planned and executed.
ResultSet: The ResultSet represents set of rows retrieved due to question execution.
Core Java Tutorial
Question 5. What Is Jdbc Driver Interface?

Answer :

The JDBC Driver interface gives seller-precise implementations of the summary lessons furnished through the JDBC API. Each supplier driver need to provide implementations of the java.Sq..Connection, Statement, Prepared Statement,  CallableStatement, ResultSet and Driver.

JSP Interview Questions
Question 6. What Does The Connection Object Represents?

Answer :

The connection object represents verbal exchange context, i.E., all conversation with database is through connection item only.

Question 7. What Is Statement ?

Answer :

Statement acts like a car thru which SQL instructions may be sent. Through the relationship object we create declaration sort of objects.
Through the connection item we create announcement form of gadgets.
Statement stmt = conn.CreateStatement();
This technique returns item which implements announcement interface.
JSP Tutorial Java Servlets Interview Questions
Question eight. What Is Preparedstatement?

Answer :

A prepared announcement is an SQL assertion that is precompiled by using the database. Through precompilation, prepared statements enhance the performance of SQL instructions which are finished more than one instances (for the reason that the database helps prepared statements). Once compiled, prepared statements can be customized previous to each execution by means of changing 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 example of the Connection elegance and "?" represents parameters.These parameters have to be precise before execution.

Question 9. What Are Callable Statements ?

Answer :

Callable statements are used from JDBC application to invoke stored techniques and functions.

EJB(Enterprise JavaBeans) Interview Questions
Question 10. How To Call A Stored Procedure From Jdbc ?

Answer :

PL/SQL stored processes are called from inside JDBC programs through the prepareCall() approach of the Connection item created. A call to this method takes variable bind parameters as input parameters in addition to output variables and creates an item example of the CallableStatement elegance. The following line of code illustrates this:

CallableStatement stproc_stmt = conn.PrepareCall("call procname(?,?,?)");
Here conn is an example of the Connection magnificence.


Java Servlets Tutorial
Question 11. What Are Types Of Jdbc Drivers?

Answer :

There are 4 styles of drivers described by way of JDBC as follows:

Type 1: JDBC/ODBC—These require an ODBC (Open Database Connectivity) driving force for the database to be installed. This type of driver works via translating the submitted queries into equivalent ODBC queries and forwards them via local API calls directly to the ODBC motive force. It provides no host redirection functionality.
Type2: Native API (partly-Java motive force)—This kind of driving force uses a supplier-precise motive force or database API to have interaction with the database. An instance of such an API is Oracle OCI (Oracle Call Interface). It additionally offers no host redirection.
Type 3: Open Protocol-Net—This is not seller unique and works through forwarding database requests to a far flung database supply using a internet server aspect. How the internet server thing accesses the database is transparent to the client. The patron motive force communicates with the internet server the use of a database-unbiased protocol and the net server interprets this protocol into database calls. This kind of driver can get entry to any database.
Type 4: Proprietary Protocol-Net(pure Java driver)—This has a identical configuration as a type 3 driver however makes use of a twine protocol precise to a selected seller and for this reason can access simplest that seller's database. Again that is all transparent to the purchaser.

JSTL(JSP Standard Tag Library) Interview Questions
Question 12. Which Type Of Jdbc Driver Is The Fastest One?

Answer :

JDBC Net natural Java motive force(Type IV) is the fastest motive force because it converts the JDBC calls into seller precise protocol calls and it at once interacts with the database.

Core Java Interview Questions
Question thirteen. Does The Jdbc-odbc Bridge Support Multiple Concurrent Open Statements Per Connection?

Answer :

No. You can open best one Statement item in keeping with connection whilst you are using the JDBC-ODBC Bridge.

EJB(Enterprise JavaBeans) Tutorial
Question 14. Which Is The Right Type Of Driver To Use And When?

Answer :

Type I driving force is reachable for prototyping.
Type III driving force provides safety, caching, and connection manipulate.
Type III and Type IV drivers need no pre-installation.
Question 15. What Are The Standard Isolation Levels Defined By Jdbc?

Answer :

The values are defined in the magnificence java.Sq..Connection and are:

Any given database won't assist all of those degrees.

JNDI (Java Naming and Directory Interface) Interview Questions
Question sixteen. What Is Resultset ?

Answer :

The ResultSet represents set of rows retrieved due to question execution.

ResultSet rs = stmt.ExecuteQuery(sqlQuery);
Java Bean Utils Tutorial
Question 17. What Is Rowset?

Answer :

A RowSet is an object that encapsulates a fixed of rows from both Java Database Connectivity (JDBC) result units or tabular records assets like a report or spreadsheet. RowSets support component-primarily based development fashions like JavaBeans, with a popular set of properties and an event notification .

Java Bean Utils Interview Questions
Question 18. What Are The Different Types Of Rowset ?

Answer :

There are two forms of RowSet are there. They are:

Connected - A linked RowSet object connects to the database once and stays linked till the utility terminates.
Disconnected - A disconnected RowSet item connects to the database, executes a question to retrieve the information from the database after which closes the relationship. A program may also change the records in a disconnected RowSet even as it's far disconnected. Modified information can be updated in the database after a disconnected RowSet reestablishes the connection with the database.
JSP Interview Questions
Question 19. What Is The Need Of Batchupdates?

Answer :

The BatchUpdates feature permits us to group SQL statements together and send to database server in one single journey.

AWT (Abstract Window Toolkit) Tutorial
Question 20. What Is A Datasource?

Answer :

A DataSource item is the illustration of a data source within the Java programming language. In simple phrases,

A DataSource is a facility for storing records.
DataSource can be referenced by means of JNDI.
Data Source might also factor to RDBMS, report System , any DBMS and so on..
AWT (Abstract Window Toolkit) Interview Questions
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 with the aid of reusing connections rather than growing a brand new bodily connection whenever a connection is asked.

Question 22. What's The Jdbc 3.0 Api?

Answer :

The JDBC 3.Zero API is the modern day replace of the JDBC API. It incorporates many features, inclusive of scrollable result units and the SQL:1999 records kinds.

JDBC (Java Database Connectivity) is the same old for conversation between a Java software and a relational database. The JDBC API is released in two variations; JDBC version 1.22 (released with JDK 1.1.X in bundle java.Sq.) and model 2.Zero (released with Java platform 2 in programs java.Sq. And javax.Sq.). It is a simple and powerful in large part database-independent manner of extracting and placing statistics to or from any database.

Question 23. Does The Jdbc-odbc Bridge Support The New Features In The Jdbc three.Zero Api?

Answer :

The JDBC-ODBC Bridge affords a restrained 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, which include Netscape Navigator, isn't always allowed. The JDBC-ODBC bridge doesn't allow untrusted code to name it for safety reasons. This is right as it means that an untrusted applet this is downloaded by using the browser can't stay clear of Java safety by using calling ODBC. Remember that ODBC is native code, so as soon as ODBC is called the Java programming language cannot assure that a protection violation won't occur. On the alternative hand, Pure Java JDBC drivers work properly with applets. They are fully downloadable and do not require any client-aspect configuration.

Finally, we would like to notice that it's miles viable to use the JDBC-ODBC bridge with applets that will be run in appletviewer on the grounds that appletviewer assumes that applets are relied on. In standard, it's far dangerous to turn applet protection off, however it may be appropriate in sure managed conditions, such as for applets in an effort to most effective be utilized in a at ease intranet environment. Remember to workout caution in case you choose this option, and use an all-Java JDBC driver whenever feasible to avoid safety issues.

Java Servlets Interview Questions
Question 25. How Do I Start Debugging Problems Related To The Jdbc Api?

Answer :

A excellent way to find out what JDBC calls are doing is to enable JDBC tracing. The JDBC hint includes a detailed listing of the hobby happening inside the system this is related to JDBC operations.

If you use the DriverManager facility to establish your database connection, you use the DriverManager. SetLogWriter technique to allow tracing of JDBC operations. If you use a DataSource item to get a connection, you operate the DataSource.SetLogWriter method to enable tracing. (For pooled connections, you operate the ConnectionPoolDataSource.SetLogWriter technique, and for connections which could take part in disbursed transactions, you operate the XADataSource.SetLogWriter technique.)

Question 26. What Is New In Jdbc 2.0?

Answer :

With the JDBC 2.Zero API, you'll be capable of do the subsequent:
Scroll forward and backward in a end result set or flow to a selected row (TYPE_SCROLL_ SENSITIVE, previous(), final(), absolute(), relative(), etc.) Make updates to database tables the use of techniques inside the Java programming language as opposed to the use of SQL instructions.(updateRow(), insertRow(), deleteRow(), and many others.) Send a couple of SQL statements to the database as a unit, or batch (addBatch(), executeBatch()) Use the brand 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 styles of JDBC Drivers

JDBC-ODBC Bridge Driver
Native API Partly Java Driver
Network protocol Driver
JDBC Net pure Java Driver
EJB(Enterprise JavaBeans) Interview Questions
Question 28. Can We Implement An Interface In A Jsp?

Answer :


Question 29. What Is The Difference Between Servletcontext And Pagecontext?

Answer :

ServletContext: Gives the records about the field.
PageContext: Gives the facts approximately 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 for the duration of translation time.

JSP encompass: Used to include dynamic content or static content in the course of runtime.

Question 32. What Is The Difference Between Requestdispatcher And Sendredirect?

Answer :

RequestDispatcher: server-aspect redirect with request and response objects.

SendRedirect : Client-side redirect with new request and response items.

Question 33. How Does Jsp Handle Runtime Exceptions?

Answer :

Using errorPage characteristic of page directive and also we want to specify isErrorPage=proper if the modern-day web page is meant to URL redirecting of a JSP.

JSTL(JSP Standard Tag Library) Interview Questions
Question 34. How Do You Delete A Cookie Within A Jsp?

Answer :

Cookie mycook = new Cookie("call","fee");
Cookie killmycook = new Cookie("mycook","cost");
Question 35. How Do I Mix Jsp And Ssi #consist of?

Answer :

If you’re just together with raw HTML, use the #include directive as regular interior your .Jsp record.

Question 36. I Made My Class Cloneable But I Still Get Can't Access Protected Method Clone. Why?

Answer :

Some of the Java books suggest that all you have to do as a way to have your class aid clone() is put into effect the Cloneable interface. Not so. Perhaps that changed into the purpose sooner or later, but that’s no longer the way it really works presently. As it stands, you need to implement your own public clone() technique, even supposing it doesn’t do some thing special and simply calls first rate.Clone().

JNDI (Java Naming and Directory Interface) Interview Questions
Question 37. Why Is Xml Such An Important Development?

Answer :

It removes two constraints which had been retaining back Web trends: dependence on a single, rigid file type (HTML) which become being a whole lot abused for obligations it became in no way designed for; the complexity of full SGML, whose syntax allows many effective but hard-to-application alternatives. XML lets in the bendy improvement of person-described file sorts. It affords a sturdy, non-proprietary, continual, and verifiable report layout for the garage and transmission of textual content and facts each on and rancid the Web; and it removes the greater complicated alternatives of SGML, making it less complicated to software for.

Question 38. What Is The Fastest Type Of Jdbc Driver?

Answer :

JDBC motive force performance will rely on some of issues:

the exceptional of the driver code,
the size of the motive force code,
the database server and its load,
community topology,
the wide variety of times your request is translated to a distinctive API.
In trendy, all matters being same, you can expect that the extra your request and reaction alternate arms, the slower it'll be. This manner that Type 1 and Type 3 drivers can be slower than Type 2 drivers (the database calls are make at least three translations as opposed to two), and Type 4 drivers are the fastest (only request.GetParameter("foo").Equals(""));
boolean hasParameter =
request.GetParameterMap().Consists of(theParameter); //(which goes in Servlet 2.Three+)
Question 40. How Can I Send User Authentication Information While Makingurlconnection?

Answer :

You’ll want to use HttpURLConnection.SetRequestProperty and set all the suitable headers to HTTP authorization.

Java Bean Utils Interview Questions
Question 41. How Do I Create A Database Connection?

Answer :

The database connection is created in 3 steps:

Find a right database URL.
Load the database motive force.
Ask the Java DriverManager class to open a connection for your database.
In java code, the steps are realized in code as follows:

Create a properly formatted JDBR URL for your database.  A JDBC URL has the form jdbc:someSubProtocol://myDatabaseServer/theDatabaseName
     Class.ForName("my.Database.Motive force");
       catch(Exception ex)
     System.Err.Println("Could not load database motive force: " + ex);
Connection conn = DriverManager.GetConnection("a.JDBC.URL", "databaseLogin", "databasePassword");
Question forty two. What Is Metadata And Why Should I Use It?

Answer :

Metadata ('information approximately facts') is facts approximately certainly one of  matters:

Database statistics (java.Square.DatabaseMetaData), or
Information approximately a particular ResultSet (java.Square. ResultSet MetaData).
Use DatabaseMetaData to discover statistics approximately your database, including its capabilities and shape. Use ResultSetMetaData to discover records approximately the effects of an SQL query, which includes length and forms of columns.

AWT (Abstract Window Toolkit) Interview Questions
Question 43. How Does The Java Database Connectivity (jdbc) Work?

Answer :

The JDBC is used on every occasion a Java utility have to speak with a relational database for which a JDBC driver exists. JDBC is part of the Java platform fashionable; all visible lessons used inside the Java/database communication are placed in bundle java.Square.

Main JDBC instructions:

DriverManager: Manages a list of database drivers. Matches connection requests from the java application with the proper database motive force the use of communique subprotocol. The first driver that recognizes a certain subprotocol underneath jdbc (along with odbc or dbAnywhere/dbaw) may be used to establish a database Connection.
Driver: The database communications link, handling all communique with the database. Normally, once the driving force is loaded, the developer want now not call it explicitly.
Connection: Interface with all strategies for contacting a database.
Statement: Encapsulates an SQL announcement that is passed to the database to be parsed, compiled, planned and finished.
ResultSet: The answer/result from a assertion. A ResultSet is a fancy 2D list which encapsulates all outgoing consequences from a given SQL question.
Question forty four. What Is The Advantage Of Using A Preparedstatement?

Answer :

For SQL statements that are accomplished time and again, the usage of a PreparedStatement object could almost usually be quicker than using a Statement object. This is due to the fact creating a PreparedStatement object by using explicitly giving the SQL declaration reasons the statement to be precompiled inside the database immediately. Thus, when the PreparedStatement is later executed, the DBMS does no longer need to recompile the SQL announcement and prepared an execution plan - it honestly runs the statement.

Typically, PreparedStatement items are used for SQL statements that take parameters. However, they can also be used with time and again performed SQL statements that don't receive parameters.

Question 45. How Do I Extract The Sql Statements Required To Move All Tables And Views From An Existing Database To Another Database?

Answer :

The operation is finished in 9 steps:

Open a connection to the source database. Use the DriverManager magnificence.
Find the entire bodily format of the contemporary database. Use the DatabaseMetaData interface.
Create DDL SQL statements for re-developing the present day database structure. Use the DatabaseMetaData interface.
Build a dependency tree, to decide the order in which tables have to be setup. Use the DatabaseMetaData interface.
Open a connection to the goal database. Use the DriverManager elegance.
Execute all DDL SQL statements from (three) in the order given by means of (4) in the target database to setup the table and examine structure. Use the PreparedStatement interface.
If (6) threw exceptions, abort the complete procedure.
Loop over all tables within the physical structure to generate DML SQL statements for re-growing the facts in the table. Use the ResultSetMetaData interface.
Execute all DML SQL statements from (eight) in the goal database.
Question 46. What Does Resultset Actually Contain? Is It The Actual Data Of The Result Or Some Links To Databases? If It Is The Actual Data Then Why Can't We Access It After Connection Is Closed?

Answer :

A ResultSet is an interface. Its implementation relies upon on the driving force and for this reason ,what it "incorporates" relies upon partially on the driving force and what the query returns. For example with the Odbc bridge what the underlying implementation layer incorporates is an ODBC end result set. A Type 4 driving force executing a stored process that returns a cursor - on an oracle database it truly returns a cursor inside the databse. The oracle cursor can however be processed like a ResultSet could be from the client. Closing a connection closes all interaction with the database and releases any locks that would were acquired within the technique.

Question forty seven. Can I Use The Jdbc-odbc Bridge Driver In An Applet?

Answer :


Question forty eight. How Can I Connect From An Applet To A Database On The Server?

Answer :

There are two methods of connecting to a database at the server aspect.

The tough way. Untrusted applets can not contact the tough disk of a computer. Thus, your applet can not use local or other local files (along with JDBC database drivers) for your hard drive. The first alternative answer is to create a digitally signed applet which may additionally use domestically mounted JDBC drivers, capable of connect at once to the database at the server facet.
The smooth way. Untrusted applets may also most effective open a network connection to the server from which they were downloaded. Thus, you must region a database listener (either the database itself, or a middleware server) at the server node from which the applet became downloaded. The applet might open a socket connection to the middleware server, positioned at the equal laptop node because the webserver from which the applet was downloaded. The middleware server is used as a mediator, connecting to and extract data from the database.
Question 49. How Do I Insert An Image File (or Other Raw Data) Into A Database?

Answer :

All uncooked statistics sorts (which includes binary files or pictures) need to be read and uploaded to the database as an array of bytes, byte[]. Originating from a binary report,

Read all data from the record the use of a FileInputStream.
Create a byte array from the read information.
Use technique setBytes(int index, byte[] statistics); of java.Sq..PreparedStatement to add the statistics.
Question 50. How Can Resultset Records Be Restricted To Certain Rows?

Answer :

The easy answer is "Use a JDBC 2.0 compliant motive force". With a 2.Zero motive force, you could use the setFetchSize() approach inside a Statement or a ResultSet item.
For instance,

Statement stmt = con.CreateStatement();
stmt.SetFetchSize(four hundred);
ResultSet rs = stmt.ExecuteQuery("choose * from clients");
will alternate the default fetch size to four hundred.
You also can manage the direction in which the rows are processed. For instance:
will process the rows from bottom up.
The motive force supervisor generally defaults to the most green fetch length...So that you may additionally attempt experimenting with special price for ultimate performance.

Question 51. What Is The Difference Between Client And Server Database Cursors?

Answer :

What you see on the client side is the modern-day row of the cursor which called a Result (ODBC) or ResultSet (JDBC). The cursor is a server-side entity most effective and remains on the server facet.

Question fifty two. How Can I Convert A Java Array To A Java.Square.Array?

Answer :

A Java array is a first elegance item and all of the references essentially use PreparedStatement.SetObject() or ResultSet.UpdateObject() techniques for putting the array to an ARRAY inside the database. Here's a primary instance:

String[] as =  "One", "Two", "Three" ;
PreparedStatement playstation  = 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 dedicate 
//..Your insert/replace/delete goes right here 
a new transaction is implicitly started out. JDBC 2.0 provides a fixed of methods for executing a batch of database instructions. Specifically, the java. Square. Statement interface presents three strategies: addBatch(), clearBatch() and executeBatch(). Their documentation is quite clear-cut. The implementation of these methods is non-obligatory, so ensure that your motive force supports those.


Question 54. How Can I Connect To An Oracle Database Not On The Web Server From An Untrusted Applet?

Answer :

You can use the skinny ORACLE JDBC motive force in an applet (with some extra parameters at the JDBC URL). Then, if you have NET8, you may use the connection supervisor of NET8 on the internet server to proxy the relationship request to the database server.

Question fifty five. How Do I Get Runtime Information About The Jdbc Driver?

Answer :

Use the subsequent DatabaseMetaData techniques:

Question fifty six. How Can I Determine Whether A Statement And Its Resultset Will Be Closed On A Commit Or Rollback?

Answer :

Use the DatabaseMetaData methods supportsOpen StatementsAcrossCommit() and helps Open Statements Across Rollback().

Question fifty seven. Is There A Practical Limit For The Number Of Sql Statements That Can Be Added To An Instance Of A Statement Object

Answer :

While the specification makes no point out of any size obstacle for Statement.AddBatch(), this appears to be established, as ordinary, on the driver. Among other matters, it relies upon at the form of box/series used. I recognize of at the least one driving force that makes use of a Vector and grows as wanted. I've seen questions about another driving force that looks to top somewhere among 500 and 1000 statements. Unfortunately, there doesn't appear like any metadata records concerning viable limits. Of route, in a manufacturing best motive force, one would count on an exception from an addBatch() invocation that went past the command listing's limits.

Question 58. What Does Setfetchsize() Really Do?

Answer :

The API documentation explains it quite properly, but some of programmers appear to have a misconception of its functionality. The first aspect to notice is that it is able to do not anything at all; it's far simplest a hint, even to a JDBC Compliant driving force. SetFetchSize() is sincerely a request for a certain sized blocking issue, this is, how a good deal data to send at a time.

Because journeys to the server are highly-priced, sending a bigger range of rows can be greater efficient. It may be more green at the server aspect as well, relying on the specific SQL announcement and the DB engine. That might be genuine if the data can be read immediately off an index and the DB engine paid interest to the fetch length. In that case, the DB engine could go back handiest sufficient statistics consistent with request to fit the fetch length. Don't count on that conduct. In trendy, the fetch length could be transparent on your software and simplest determines how often requests are despatched to the server as you traverse the information. Also, both Statement and ResultSet have setFetchSize techniques. If used with a Statement, all ResultSets back by that Statement will have the identical fetch size. The technique can be used at any time to exchange the fetch length for a given ResultSet. To determine the modern or default length, use the getFetchSize methods.

Question 59. What Scalar Functions Can I Expect To Be Supported By Jdbc?

Answer :

JDBC helps numeric, string, time, date, gadget, and conversion functions on scalar values. For a list of those supported and extra statistics, see section A.1.Four Support Scalar Functions in the JDBC Data Access API For Driver Writers. Note that drivers are handiest predicted to help the ones scalar capabilities which are supported by using the underlying DB engine.

Question 60. What Does Normalization Mean For Java.Sq..Date And Java.Square.Time?

Answer :

These training are skinny wrappers extending java.Util.Date, which has each date and time additives. Java.Sq..Date must bring handiest date information and a normalized instance has the time information set to zeros. Java.Square.Time must carry handiest time facts 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 lets in retrieval. Keep in thoughts that earlier ResultSet warnings are cleared on every new read and earlier Statement warnings are cleared with each new execution. GetWarnings() itself does no longer clean present warnings, but every item has a clearWarnings technique.

Question 62. How Can I Investigate The Physical Structure Of A Database?

Answer :

The JDBC view of a database inner structure can be seen in the photograph underneath.

Several database objects (tables, views, techniques etc.) are contained within a Schema.
Several schema (person namespaces) are contained inside a catalog.
Several catalogs (database walls; databases) are contained within a DB server (which includes Oracle, MS SQL.
The DatabaseMetaData interface has methods for discovering all the Catalogs, Schemas, Tables and Stored Procedures inside the database server. The techniques are quite intuitive, returning a ResultSet with a unmarried String column; use them as indicated in the code underneath:

public static void fundamental(String[] args) throws Exception

// Load the database driver - in this situation, we
// use the Jdbc/Odbc bridge driver.
// 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 referred to as '" + dbmd.GetCatalogTerm() 
+ "' on this RDBMS.");
processResultSet(dbmd.GetCatalogTerm(), dbmd.GetCatalogs()); 
// Get all Schemas
System.Out.Println("nSchemas are known as '" + dbmd.GetSchemaTerm()
+ "' in this RDBMS.");
processResultSet(dbmd.GetSchemaTerm(), dbmd.GetSchemas()); 
// Get all Table-like sorts
System.Out.Println("nAll table kinds supported in this RDBMS:");
processResultSet("Table kind", dbmd.GetTableTypes());
// Close the Connection

public static void processResultSet(String preamble, ResultSet rs) 
throws SQLException

// Printout table facts
at the same time as(rs.Subsequent())

// Printout
System.Out.Println(preamble + ": " + rs.GetString(1));

// Close database assets

Question 63. How Do I Find All Database Stored Procedures In A Database?

Answer :

Use the getProcedures approach of interface java.Sq..DatabaseMetaData to probe the database for saved processes. The specific usage is described inside the code beneath.

Public static void most important(String[] args) throws Exception

// Load the database motive force - in this situation, we
// use the Jdbc/Odbc bridge motive force.
// Open a connection to the database
Connection conn = DriverManager.GetConnection("[jdbcURL]",  "[login]", "[passwd]");
// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.GetMetaData();
// Get all methods.
System.Out.Println("Procedures are referred to as '"  + dbmd.GetProcedureTerm() +"' within the DBMS.");
ResultSet rs = dbmd.GetProcedures(null, null, "%");
// Printout desk facts
even as(rs.Next())

// Get process metadata
String dbProcedureCatalog = rs.GetString(1);
String dbProcedureSchema = rs.GetString(2);
String dbProcedureName = rs.GetString(3);
String dbProcedureRemarks = rs.GetString(7);
quick dbProcedureType = rs.GetShort(8);
// Make result readable for humans " + dbProcedureSchema + "]");
System.Out.Println(" Comments: " + dbProcedureRemarks);

// Close database resources

Question 64. How Do I Check What Table Types Exist In A Database?

Answer :

Use the getTableTypes approach of interface java.Square.DatabaseMetaData to probe the database for desk types. The exact usage is defined within the code underneath.

Public static void main(String[] args) throws Exception

// Load the database motive force - in this example, we
// use the Jdbc/Odbc bridge driving force.
// Open a connection to the database
Connection conn = DriverManager.GetConnection("[jdbcURL]", "[login]", "[passwd]");
// Get DatabaseMetaData
DatabaseMetaData dbmd = conn.GetMetaData();
// Get all table kinds.
ResultSet rs = dbmd.GetTableTypes();
// Printout table facts
even as(rs.Subsequent())

// Printout
System.Out.Println("Type: " + rs.GetString(1));

// Close database assets

Question 65. How Do I Extract A Blob From A Database?

Answer :

A BLOB (Binary Large OBject) is basically an array of bytes (byte[]), saved within the database. You extract the records in  steps:

Call the getBlob method of the Statement class to retrieve a java.Square.Blob item.
Call both getBinaryStream or getBytes within the extracted Blob object to retrieve the java byte[] that is the Blob object.
Note that a Blob is essentially a pointer to a byte array (called LOCATOR in database-speak), so the java.Square.Blob item basically wraps a byte pointer. Thus, you must extract all records from the database blob earlier than calling dedicate or

<div align="center">
personal void runGetBLOB()

 // Prepare a Statement:
PreparedStatement stmnt = conn.PrepareStatement("pick out aBlob from BlobTable");
// Execute
ResultSet rs = stmnt.ExecuteQuery();


// Get as a BLOB
Blob aBlob = rs.GetBlob(1);
byte[] allBytesInBlob = aBlob.GetBytes(1, (int) aBlob.Length());

catch(Exception ex)

// The motive force couldn't cope with this as a BLOB...
// Fallback to default (and slower) byte[] managing
byte[] bytes = rs.GetBytes(1);

// Close sources

seize(Exception ex)

this.Log("Error whilst trying to read BLOB: " + ex);

Question 66. Which Is The Preferred Collection Class To Use For Storing Database Result Sets?

Answer :

When retrieving database results, the excellent collection implementation to use is the LinkedList. The benefits encompass:

Retains the unique retrieval order
Has brief insertion at the top/tail
Doesn't have an internal size quandary like a Vector where while the scale is exceeded a brand new inner shape is created (or you need to discover size in advance to size nicely)
Permits consumer-managed synchronization in contrast to the pre-Collections Vector which is continually synchronized.
ResultSet result = stmt.ExecuteQuery("...");
List listing = new LinkedList();
while(end result.Next())  
list.Add(end result.GetString("col")); 

If there are more than one columns within the result set, you will need to integrate them into their very own records shape for each row. Arrays work well for that as you know the scale, although a custom elegance is probably high-quality so that you can convert the contents to the right type when extracting from databse, rather than later.

Question 67. How Can I Get Data From Multiple Resultsets?

Answer :

With sure database structures, a saved procedure can go back multiple end result sets, more than one replace counts, or a few mixture of each. Also, in case you are presenting a consumer with the capacity to go into any SQL assertion, you don't know if you are going to get a ResultSet or an replace remember back from every statement, without analyzing the contents. The Statement.Execute() method enables in those cases.

Method Statement.Execute() returns a boolean to tell you the sort of response:

actual shows subsequent end result is a ResultSet
Use Statement.GetResultSet to get the ResultSet

false suggests next result is an update count number
Use Statement.GetUpdateCount to get the replace be counted

false also indicates no greater results
Update rely is -1 whilst no extra results (usually 0 or wonderful)

After processing each reaction, you operate Statement.GetMoreResults to check for more results, once more returning a boolean. The following demonstrates the processing of a couple of result sets:

boolean result = stmt.Execute(" ... ");
int updateCount = stmt.GetUpdateCount();
whilst (result 
if(end result) 
ResultSet r = stmt.GetResultSet();
// process end result set
 else if(updateCount != -1) 
// manner update depend

result = stmt.GetMoreResults(); 
updateCount = stmt.GetUpdateCount();

Question sixty eight. What Are The Components Of The Jdbc Url For Oracle's "skinny" Driver And How Do I Use Them?

Answer :

Briefly: jdbc:oracle:skinny:@hostname:port:oracle-sid

in inexperienced the Oracle sub-protocol (can be oracle:oci7:@, oracle:oci8:@, racle:skinny:@, and many others...) is related at the motive force you're unsign and the protocol to talk with server.
In red the network system call, or its ip cope with, to discover the server where oracle is strolling.
In blue the port (it's far complementary to the address to choose the unique oracle carrier)
in magenta the sid, pick out on which database you want to connect.
Here's an instance:
where consumer=scott and pass=tiger.
Question 69. I Need To Have Result Set On A Page Where The User Can Sort On The Column Headers. Any Ideas?

Answer :

One opportunity: Have an elective discipline to your shape or GET url called (correctly) ORDER with a default value of both "no order" or anything you want your default ordering to be (i.E. Timestamp, username, something). When you get your request, see what the fee of the ORDER element is. If it is null or blank, use the default. Use that value to build your SQL query, and show the results to the page. If you are caching data on your servlet, you may use the Collection framework to sort your statistics (see java.Util.Collections) if you may get it into a List format. Then, you may create a Collator which could impose a total ordering to your outcomes.

Question 70. What's The Best Way, In Terms Of Performance, To Do Multiple Insert/replace Statements, A Preparedstatement Or Batch Updates?

Answer :

Because PreparedStatement objects are precompiled, their execution can be faster than that of Statement objects. Consequently, an SQL statement that is performed regularly is frequently created as a PreparedStatement object to boom efficiency. A CallableStatement item offers a manner to name saved approaches in a popular manner for all DBMSes. Their execution can be faster than that of PreparedStatement item. Batch updates are used when you need to execute multiple statements together. Actually, there is no warfare here. While it depends at the driver/DBMS engine as to whether or no longer you may get an real overall performance benefit from batch updates, Statement, PreparedStatement, and CallableStatement can all execute the addBatch() approach.

Question 71. What Is Jdo?

Answer :

JDO presents for the obvious staying power of data in a information save agnostic way, helping object, hierarchical, in addition to relational shops.

Question seventy two. What Is The Difference Between Setmaxrows(int) And Setfetchsize(int)? Can Either Reduce Processing Time?

Answer :

setFetchSize(int) defines the wide variety of rows a good way to be study from the database while the ResultSet wishes extra rows. The approach inside the java.Square.Statement interface will set the 'default' price for all the ResultSet derived from that Statement; the technique inside the java.Sq..ResultSet interface will override that fee for a particular ResultSet. Since database fetches may be high-priced in a networked environment, fetch size has an effect on performance.

SetMaxRows(int) sets the restrict of the maximum nuber of rows in a ResultSet object. If this restriction is surpassed, the excess rows are "silently dropped". That's all the API says, so the setMaxRows method might not assist performance in any respect aside from to decrease memory utilization. A price of zero (default) approach no restrict. Since we are speaking approximately interfaces, be careful due to the fact the implementation of drivers is regularly extraordinary from database to database and, in some cases, may not be applied or have a null implementation. Always seek advice from the driver documentation.

Question 73. How Can I Tell If My Jdbc Driver Normalizes Java.Sq..Date And Java.Sq..Time Objects?

Answer :

To truly determine the values, the gadgets must be transformed to a java.Util.Date and examined. See What does normalization imply for java.Square.Date and java.Square.Time? For the definition of normalization. Notice that even a debugger will not display whether or not these items have been normalized, for the reason that getXXX methods in java.Square.Date for time factors and in java.Square.Time for date elements throw an exception.

So, whilst a java.Sq..Date may additionally display 2001-07-26, it is normalized handiest if the java.Util.Date cost is:
Thu Jul 26 00:00:00 EDT 2001

and while a java.Sq..Time may additionally display 14:01:00, it's normalized handiest if the java.Util.Date value is:
Thu Jan 01 14:01:00 EST 1970

Question seventy four. Can I Get Information About A Resultset's Associated Statement And Connection In A Method Without Having Or Adding Specific Arguments For The Statement And Connection?

Answer :

Yes. Use ResultSet.GetStatement(). From the ensuing Statement you may use Statement.GetConnection().

Question seventy five. What Is Pessimistic Concurrency?

Answer :

With a pessimistic method, locks are used to ensure that no customers, aside from the one who holds the lock, can replace facts. It's commonly defined that the term pessimistic is used due to the fact the expectancy is that many users will attempt to update the same facts, so one is pessimistic that an update can be able to finish properly. Locks can be received, depending at the DBMS dealer, automatically through the chosen Isolation Level. Some vendors also enforce 'Select... For Update', which explicitly acquires a lock.

Question 76. What Is Optimistic Concurrency?

Answer :

An positive approach dispenses with locks ( except during the actual replace ) and typically includes comparison of timestamps, or generations of records to make certain that information hasn't changed among get admission to and replace instances. It's typically explained that the term optimistic is used due to the fact the expectancy is that a clash between multiple updates to the same statistics 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 can wrap your SQL related code in a custom magnificence and throw something like ObjectNotFoundException when the back ResultSet is empty.

Question seventy eight. What Is Connection Pooling?

Answer :

Connection pooling is a method used for sharing server resources amongst requesting customers. Connection pooling increases the performance of Web programs by using reusing energetic database connections in preference to developing a brand new reference to each request. Connection pool supervisor keeps a pool of open database connections.

Question 79. Which Java And Java.Square Data Types Map To My Specific Database Types?

Answer :

JDBC is, of necessity, reliant at the driving force and underlying DBMS. These do no longer usually adhere to requirements as intently as we would really like, inclusive of differing names for preferred Java sorts. To address this, first, there are a number of tables to be had in the JDK JDBC documentation handling sorts.

Question 80. Does The Database Server Have To Be Running Java Or Have Java Support In Order For My Remote Jdbc Client App To Access The Database?

Answer :

The answer ought to usually be no. The two essential necessities are LAN/internet connectivity and the appropriate JDBC driver. Connectivity is generally via TCP/IP, but other communique 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 task to transform the SQL statements and JDBC calls to the DBMS' local protocol. From the server's point of view, it's simply every other statistics request entering the port, the programming language used to send the information is irrelevant at that point.

Question eighty one. What Is A Jdbc 2.Zero Datasource?

Answer :

The DataSource class become added inside the JDBC 2.0 Optional Package as an less complicated, more typical way of obtaining a Connection. The real driver providing offerings is described to the DataSource outdoor the application ( Of route, a production first-rate app can and have to provide this records outside the app anyway, generally with properties files or ResourceBundles ). The documentation expresses the view that DataSource will update the not unusual DriverManager method.

Question eighty two. What Types Of Datasource Objects Are Specified In The Optional Package?

Answer :

Basic - Provides a fashionable Connection item.
Pooled - Provides a Connection pool and returns a Connection that is managed with the aid of the pool.
Distributed - Provides a Connection which could participate in disbursed transactions ( multiple DBMS is involved). It is predicted, but now not enforced, that a allotted DataSource may even provide pooling.
However, there are not any widespread techniques available inside the DataSource elegance to determine if one has obtained a pooled and/or allotted Connection.

Question eighty three. What Is The Significance Of Databasemetadata.Tableindexstatistics? How To Obtain And Use It?

Answer :

To answer the second query first, the tableIndexStatistic constant in the TYPE column will identify one of the rows within the ResultSet returned while DatabaseMetaData.GetIndexInfo() is invoked. If you analyze the wordy API, a tableIndexStatistic row will include the number of rows in the desk within the CARDINALITY column and the wide variety of pages used for the table in the PAGES column.

Question eighty four. What Is Dml?

Answer :

DML is an abbreviation for Data Manipulation Language. This part of the SQL preferred is concerned with manipulating the records in a database in preference to the structure of a database. The center verbs for DML are SELECT, INSERT, DELETE, UPDATE, COMMIT and ROLLBACK.

Question eighty five. Can I Use Jdbc To Execute Non-fashionable Features That My Dbms Provides?

Answer :

The solution is a qualified yes. As mentioned underneath SQL Conformance: "One way the JDBC API offers with this trouble is to permit any question string to be surpassed via to an underlying DBMS motive force. This means that an software is free to use as plenty SQL functionality as preferred, however it runs the threat of receiving an error on some DBMSs. In truth, an utility query can be something apart from SQL, or it may be a specialised by-product of SQL designed for specific DBMSs (for report or picture queries, as an instance)."

Clearly this indicates either giving up portability or checking the DBMS presently used earlier than invoking precise operations.

Question 86. How Can I Get Information About Foreign Keys Used In A Table?

Answer :

DatabaseMetaData.GetImportedKeys() returns a ResultSet with statistics about foreign key columns, tables, series and replace and delete policies.

Question 87. How Can I Determine Where A Given Table Is Referenced Via Foreign Keys?

Answer :

DatabaseMetaData.GetExportedKeys() returns a ResultSet with records similar to that returned through Database MetaData .GetImported Keys(), except that the facts relates to different 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 continually deal with multiple declaration and a transaction is frequently defined as a Logical Unit of Work ( LUW ). The rationale for transactions is which you need to realize definitively that all or none of the LUW completed efficiently. Note that this mechanically gives you restart capability. Typically, there are  situations below which you could want to apply transactions:

Multiple statements involving a single record - An example might be putting all of a group of rows or all fee updates for a given date. You want all of these to take effect at the same time; inserting or changing some subset isn't always acceptable.
Multiple statements regarding multiple files - The classic example is shifting money from one account to every other or double entry accounting; you do not want the debit to be triumphant and the credit score to fail due to the fact money or vital information can be lost. Another example is a grasp/element relationship, wherein, say, the grasp contains a complete column. If t