How many types of JDBC Drivers are present and what are they? JDBC drivers are divided into four types or levels. The different types of jdbc drivers are: Type 1: JDBC-ODBC Bridge driver (Bridge) Type 2: Native-API/partly Java driver (Native) Type 3: All Java/Net-protocol driver (Middleware) Type 4: All Java/Native-protocol driver (Pure) What Class.forName will do while loading drivers? It is used to create an instance of a driver and register it with the Driver Manager. When you have loaded a driver, it is available for making a connection with a DBMS. What are stored procedures? How is it useful? A stored procedure is a set of statements/commands which reside in the database. The stored procedure is pre-compiled and saves the database the effort of parsing and compiling sql statements every time a query is run. Each database has its own stored procedure language, usually a variant of C with a SQL preprocessor. Before the advent of 3-tier/n-tier architecture it was pretty common for stored procedures to implement the business logic (A lot of systems still do it). The biggest advantage is of course speed. Also certain kinds of data manipulations are not achieved in SQL. Stored procedures provide a mechanism to do these manipulations. Stored procedures are also useful when you want to do Batch updates/exports kind of stuff on the db. The overhead of a JDBC Connection may be significant in these cases. How to call a Stored Procedure from JDBC? The first step is to create a CallableStatement object. As with Statement and PreparedStatement objects, this is done with an open Connection object. A CallableStatement object contains a call to a stored procedure. CallableStatement cs = con.preparecall("{call SHOW_SUPPLIERS}"); ResultSet rs = cs.executequery(); The part that is enclosed in curly braces is the escape syntax for stored procedures. When the driver encounters "{call SHOW_SUPPLIERS}", it will translate this escape syntax into the native SQL used by the database to call the stored procedure named SHOW_SUPPLIERS. Is the JDBC-ODBC Bridge multi-threaded? 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. Multithreaded Java programs may use the Bridge, but they won't get the advantages of multi-threading. What is the advantage of using PreparedStatement? If we are using PreparedStatement the execution time will be less. This is because PreparedStatement object contains SQL statement that has been precompiled. 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. What is a "dirty read"?
Quite often in database processing, we come across the situation wherein one transaction can change a value, and a second transaction can read this value before the original change has been committed or rolled back. This is known as a dirty read scenario because there is always the possibility that the first transaction may rollback the change, resulting in the second transaction having read an invalid value. What are different types of isolation levels in JDBC and explain where you can use them? Five types of isolation levels are as follows: 1. TRANSACTION_READ_COMMITED If the application needs only committed records, then TRANSACTION_READ_COMMITED isolation is the good choice. 2. TRANSACTION_REPEATABLE_READ If the application needs to read a row exclusively till you finish your work, then TRANSACTION_REPEATABLE_READ is the best choice. 3. TRANSACTION_SERIALIZABLE If the application needs to control all of the transaction problems (dirty read, phantom read and unrepeatable read), you can choose TRANSACTION_SERIALIZABLE for maximum safety. 4. TRANSACTION_NONE If the application doesn t have to deal with concurrent transactions, then the best choice is TRANSACTION_NONE to improve performance. 5. TRANSACTION_READ_UNCOMMITED If the application is searching for records from the database then you can easily choose TRANSACTION_READ_UNCOMMITED because you need not worry about other programs that are inserting records at the same time. What are the different types of statements in JDBC? The JDBC API has 3 Statements 1. Statement, 2. PreparedStatement, 3. CallableStatement. The key features of these are as follows: Statement 1. This interface is used for executing a static SQL statement and returning the results it produces. 2. The object of Statement class can be created using Connection.createStatement() method. PreparedStatement 1. A SQL statement is pre-compiled and stored in a PreparedStatement object. 2. This object can then be used to efficiently execute this statement multiple times. 3. The object of PreparedStatement class can be created using Connection.prepareStatement() method. This extends Statement interface.
CallableStatement 1. This interface is used to execute SQL stored procedures. 2. This extends PreparedStatement interface. 3. The object of CallableStatement class can be created using Connection.prepareCall() method. What is JDBC? JDBC may stand for Java Database Connectivity. It is also a trade mark. JDBC is a layer of abstraction that allows users to choose between databases. It allows you to change to a different database engine and to write to a single API. JDBC allows you to write database applications in Java without having to concern yourself with the underlying details of a particular database. What are the common tasks of JDBC? Common tasks of JDBC are as follows: 1. Create an instance of a JDBC driver or load JDBC drivers through jdbc.drivers 2. Register a driver 3. Specify a database 4. Open a database connection 5. Submit a query 6. Receive result 7. Process result What interfaces are used by JDBC? List of interfaces used by JDBC with description are as follows: Interface java.sql.connection java.sql.databasemetadata java.sql.driver java.sql.preparedstatement java.sql.resultset java.sql.resultsetmetadata java.sql.statement javax.sql.connectioneventlistener javax.sql.connectionpooldatasource javax.sql.datasource javax.sql.pooledconnection Description Interface used to establish a connection to a database. SQL statements run within the context of a connection. Interface used to return information about the database. Interface used to locate the driver for a particular database management system. Interface used to send precompiled SQL statements to the database server and obtain results. Interface used to process the results returned from executing an SQL statement. Interface used to return information about the columns in a ResultSet object. Interface used to send static SQL statements to the database server and obtain results. Receives events that a PooledConnection object generates. Factory for PooledConnection objects. A ConnectionPoolDataSource object is usually registered with a JNDI service. A factory for Connection objects. A DataSource object is usually registered with a JNDI service provider. A PooledConnection object represents a physical connection to a data source. How can you Load the JDBC driver? To load the driver, you need to load the appropriate class, make a driver instance and register it with the JDBC driver manager. Use Class.forName(String) method. This method takes a string representing a fully qualified class name and loads the corresponding class. Here is an example: try { Class.forName("connect.microsoft.MicrosoftDriver"); } catch(classnotfoundexception e) {
} System.err.println("Error loading driver: " + e); The string taken in the Class.forName() method is the fully qualified class name. You should pay attention to the CLASSPATH setting. If the JDBC driver vendors distribute their drivers in a JAR file, be sure to include the JAR file in your CLASSPATH setting. How can you make the connection? Connection is made using following Method getconnection(string url, String username, String password); This method establishes a connection to specified database url. It takes following three string types of arguments. url: Database url where stored or created your database username: User name of MySQL password: Password of MySQL Include following code block to make a connection and create Statement. try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:dumy"; "user", "pass"); Statement stmt = con.createstatement(); }catch( Exception e ) { e.printstacktrace(); } How can you create JDBC statements? Using Statement interface we can create JDBC statements as follows Statement stmt = con.createstatement(); //con is the connection object reference Different types of statements are: Prepared Statement - whenever we want to execute single query multiple times then we will go to this statement Callable Statement - whenever we want to call the stored procedures from database Server then we will use this statement What's the difference between a primary key and a unique key? Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesn't allow NULLs, but unique key allows one NULL only. How to make a query?
Create a Statement object and calls the Statement.executeQuery method to select data from the database. The result of the query are returned in a ResultSet object. Statement stmt = con.createstatement(); ResultSet result = stmt.executequery("select data FROM table"); How can you retrieve data from the ResultSet? Use get methods to retrieve data from returned ResultSet object. Statement stmt = null; String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES"; try { stmt = con.createstatement(); ResultSet rs = stmt.executequery(query); while (rs.next()) { // fetch data from resultset using get methods String coffeename = rs.getstring("cof_name"); int supplierid = rs.getint("sup_id"); float price = rs.getfloat("price"); int sales = rs.getint("sales"); int total = rs.getint("total"); } } catch (SQLException e ) { JDBCTutorialUtilities.printSQLException(e); } finally { if (stmt!= null) { stmt.close(); } } The method getstring is invoked on the ResultSet object rs, so getstring will retrieve (get) the value stored in the column COF_NAME in the current row of rs. How to navigate the ResultSet? By default the result set cursor points to the row before the first row of the result set. A call to next() retrieves the first result set row. The cursor can also be moved by calling one of the following ResultSet methods: beforefirst(): Puts cursor before the first row of the result set. first(): Puts cursor on the first row of the result set. last(): Puts cursor before the last row of the result set. afterlast(): Puts cursor beyond last row of the result set. absolute(pos): Puts cursor at the row number position where absolute(1) is the first row and absolute(-1) is the last row. relative(pos): Puts cursor at a row relative to its current position where relative(1) moves row cursor one row forward. How to update a ResultSet?
An updatable result set allows modification to data in a table through the result set. You can update a value in a result set by calling the ResultSet Update Methods on the row where the cursor is positioned. The type value here is the same used when retrieving a value from the result set, for example, updatestring updates a String value and updatedouble updates a double value in the result set. rs.updatedouble("balance", rs.getdouble("balance") - 5.00); The update applies only to the result set until the call to rs.updaterow(), which updates the underlying database. To delete the current row, use rs.deleterow(). To insert a new row, use rs.movetoinsertrow(). What are the Large object types supported by Oracle? Blob and Clob. How can you use PreparedStatement? The advantage to this is that in most cases, this SQL statement will be sent to the DBMS right away, where it will be compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has been precompiled. This means that when the PreparedStatement is executed, the DBMS can just run the PreparedStatement 's SQL statement without having to compile it first. PreparedStatement updatesales = con.preparestatement( "UPDATE COFFEES SET SALES =? WHERE COF_NAME LIKE?"); Use PreparedStatement object setter methods to set the values for place holders. How to set a scroll type? Both Statements and PreparedStatements have an additional constructor that accepts a scroll type and an update type parameter. The scroll type value can be one of the following values: ResultSet.TYPE_FORWARD_ONLY: Default behavior in JDBC 1.0, application can only call next() on the result set. ResultSet.SCROLL_SENSITIVE: ResultSet is fully navigable and updates are reflected in the result set as they occur. ResultSet.SCROLL_INSENSITIVE: Result set is fully navigable, but updates are only visible after the result set is closed. You need to create a new result set to see the results. How to set update type parameter? To set update type parameter in the constructors of Statements and PreparedStatements, you may use ResultSet.CONCUR_READ_ONLY: The result set is read only. ResultSet.CONCUR_UPDATABLE: The result set can be updated.
How to do a batch job? By default, every JDBC statement is sent to the database individually. To send multiple statements at one time, use addbatch() method to append statements to the original statement and call executebatch() method to submit entire statement. Statement stmt = con.createstatement(); stmt.addbatch("update registration set balance=balance-5.00 where theuser="+theuser); stmt.addbatch("insert into auctionitems(description, startprice) " + "values("+description+","+startprice+")");... int[] results = stmt.executebatch(); The return result of the addbatch() method is an array of row counts affected for each statement executed in the batch job. If a problem occurred, a java.sql.batchupdateexception is thrown. An incomplete array of row counts can be obtained from BatchUpdateException by calling its getupdatecounts() method. How to use meta data to check a column type? Use getmetadata().getcolumntype() method to check data type. For example to retrieve an Integer, you may check it first: int count=0; Connection con=getconnection(); Statement stmt= con.createstatement(); stmt.executequery("select counter from atable"); ResultSet rs = stmt.getresultset(); if(rs.next()) { if(rs.getmetadata().getcolumntype(1) == Types.INTEGER) { Integer i = (Integer)rs.getObject(1); count = i.intvalue(); } } rs.close(); Why cannot java.util.date match with java.sql.date? Because java.util.date represents both date and time. SQL has three types to represent date and time. java.sql.date -- (00/00/00) java.sql.time -- (00:00:00) java.sql.timestamp -- in nanoseconds Note that they are subclasses of java.util.date. How to convert java.util.date value to java.sql.date? Use the code below: Calendar currenttime=calendar.getinstance(); java.sql.date startdate= new java.sql.date((currenttime.gettime()).gettime()); OR SimpleDateFormat template = new SimpleDateFormat("yyyy-MM-dd");
java.util.date enddate = new java.util.date("10/31/99"); java.sql.date sqldate = java.sql.date.valueof(template.format(enddate)); What does setautocommit do? When a connection is created, it is in auto-commit mode. This means that each individual SQL statement is treated as a transaction and will be automatically committed right after it is executed. The way to allow two or more statements to be grouped into a transaction is to disable auto-commit mode: con.setautocommit(false); Once auto-commit mode is disabled, no SQL statements will be committed until you call the method commit explicitly. con.setautocommit(false); PreparedStatement updatesales = con.preparestatement( "UPDATE COFFEES SET SALES =? WHERE COF_NAME LIKE?"); updatesales.setint(1, 50); updatesales.setstring(2, "Colombian"); updatesales.executeupdate(); PreparedStatement updatetotal = con.preparestatement("update COFFEES SET TOTAL=TOTAL +? WHERE COF_NAME LIKE?"); updatetotal.setint(1, 50); updatetotal.setstring(2, "Colombian"); updatetotal.executeupdate(); con.commit(); con.setautocommit(true); What is the difference among "dropping a table", "truncating a table" and "deleting all records" from a table? Dropping: Table structure + Data are deleted. Invalidates the dependent objects and drops the indexes Truncating: Data alone deleted. Performs an automatic commit and faster than delete. Delete: Data alone deleted. Doesn t perform automatic commit What are cursors? Explain different types of cursors. What are the disadvantages of cursors? How can you avoid cursors? Cursors allow row-by-row prcessing of the resultsets. Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. Disadvantages of cursors:
A) In cursors each time you fetch a new row it does a round trip with the database thereby increase network use and time. B) There is also restriction on select statements that can be used in cursors C) It also uses more resources and temporary memory Cursors can be avoided with the help of careful implementation of while loop and other set based operations. What are triggers? How to invoke a trigger on demand? Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table. Triggers can't be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on which they are defined. Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster. DBC ODBC Connection In Java In this section we will read about the various aspects of JDBC ODBC such as, JDBC-ODBC bridge, JDBC ODBC connection, how to create DSN etc. JDBC-ODBC Bridge As its name JDBC-ODBC bridge, it acts like a bridge between the Java Programming Language and the ODBC to use the JDBC API. To use the JDBC API with the existing ODBC Sun Microsystems (Now Oracle Corporation) provides the driver named JdbcOdbcDriver. Full name of this class is sun.jdbc.odbc.jdbcodbcdriver. JDBC ODBC Connection To Connect the JDBC and ODBC we should have a database. Then we would be required to create a DSN to use JDBC ODBC Bridge driver. The DSN (Data Source Name) specifies the connection of an ODBC to a specific server. How To Create DSN In Java. To create a DSN we would be required to follow some basic steps. These steps are as follows : Here I am using the MS-Access as database system. Before creating DSN to use MS-Access with JDBC technology the database file should be created in advance. First step is to go through the Control Panel -> Administrative Tools -> Data Sources (ODBC).
Go to the tab System DSN in the ODBC Data Source Administrator dialog box then, Click on Add button -> select MS Access Driver (*.mdb) -> click on Finish button. In the next step a dialog box ODBC Microsoft Access Setup will be opened then provide the field's values corresponding to the field's label (i.e. provide the DSN name as you wish) and then click on the "Select" button. In the next step a new dialog box "Select database" will be opened. Here you have to select the directory where you have stored your file and provide the name in the place of the Database Name and then press ok -> ok -> ok.