JDBC drivers are divided into four types or levels. The different types of jdbc drivers are:

Similar documents
Introduction to Databases

You write standard JDBC API application and plug in the appropriate JDBC driver for the database the you want to use. Java applet, app or servlets

JAVA AND DATABASES. Summer 2018

JDBC - INTERVIEW QUESTIONS

Persistency Patterns. Repository and DAO

UNIT III - JDBC Two Marks

Cyrus Shahabi Computer Science Department University of Southern California C. Shahabi

Application Programming for Relational Databases

JDBC MOCK TEST JDBC MOCK TEST IV

Databases 2012 Embedded SQL

Unit 3 - Java Data Base Connectivity

JDBC 3.0. Java Database Connectivity. 1 Java

Database connectivity (II)

JDBC Architecture. JDBC API: This provides the application-to- JDBC Manager connection.

3) execute() Usage: when you cannot determine whether SQL is an update or query return true if row is returned, use getresultset() to get the

Questions and Answers. A. A DataSource is the basic service for managing a set of JDBC drivers.

SQL: Programming Midterm in class next Thursday (October 5)

Database Programming Overview. COSC 304 Introduction to Database Systems. Database Programming. JDBC Interfaces. JDBC Overview

SNS COLLEGE OF ENGINEERING, Coimbatore

Lecture 2. Introduction to JDBC

Three-Tier Architecture

Unit 2 JDBC Programming

O ne of the most important features of JavaServer

e-pg Pathshala Subject: Computer Science Paper: Web Technology Module: JDBC INTRODUCTION Module No: CS/WT/26 Quadrant 2 e-text

Self-test Database application programming with JDBC

CSCC43H: Introduction to Databases. Lecture 9

Top 50 JDBC Interview Questions and Answers

Enterprise Java Unit 1- Chapter 6 Prof. Sujata Rizal

JDBC Drivers Type. JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server.

JDBC BASIC 19/05/2012. Objectives. Java Database Connectivity. Definitions of JDBC. Part 1. JDBC basic Working with JDBC Adv anced JDBC programming

Java E-Commerce Martin Cooke,

Kyle Brown Knowledge Systems Corporation by Kyle Brown and Knowledge Systems Corporation

ERwin and JDBC. Mar. 6, 2007 Myoung Ho Kim

Introduction to JDBC. Lecture 12

JDBC [Java DataBase Connectivity]

SQL: Programming. Announcements (September 25) Motivation. CPS 116 Introduction to Database Systems. Pros and cons of SQL.

Instructor: Jinze Liu. Fall 2008

Index. & (ampersand), specifying connection properties, 121? (question mark), specifying connection properties, 121

Java and the Java DataBase Connectivity (JDBC) API. Todd Kaufman April 25, 2002

UNIT-3 Java Database Client/Server

The Design of JDBC The Structured Query Language Basic JDBC Programming Concepts Query Execution Scrollable and Updatable Result Sets

JDBC. Oracle ODBC SP API SP API. SQL server C function calls. SQL server ODBC SP API. Oracle DSN Oracle ODBC Oracle

CSC System Development with Java. Database Connection. Department of Statistics and Computer Science. Budditha Hettige

Database Application Development

Sun Microsystems Inc. JDBC TM 2.1 API

Locking, concurrency, and isolation

DATABASE DESIGN I - 1DL300

Java Database Connectivity

Calling SQL from a host language (Java and Python) Kathleen Durant CS 3200

Secure Programming. CS3524 Distributed Systems Lecture 16

DB I. 1 Dr. Ahmed ElShafee, Java course

Chapter 16: Databases

Announcements. SQL: Part IV. Transactions. Summary of SQL features covered so far. Fine prints. SQL transactions. Reading assignments for this week

Database Access with JDBC. Dr. Jens Bennedsen, Aarhus University, School of Engineering Aarhus, Denmark

JDBC Installation Transactions Metadata

Part I: Stored Procedures. Introduction to SQL Programming Techniques. CSC 375, Fall 2017

Database Application Development

Introduction to SQL & Database Application Development Using Java

INTRODUCTION TO JDBC - Revised spring

Logging and Recovery. 444 Section, April 23, 2009

Overview. Database Application Development. SQL in Application Code. SQL in Application Code (cont.)

Database Application Development

Database Application Development

Copyright 2016 Ramez Elmasri and Shamkant B. Navathe

Outline. Lecture 10: Database Connectivity -JDBC. Java Persistence. Persistence via Database

JDBC, Transactions. Niklas Fors JDBC 1 / 38

INTRODUCTION TO JDBC - Revised Spring

Chapter 13 Introduction to SQL Programming Techniques

Chapter 3 DB-Gateways

JDBC. Sun Microsystems has included JDBC API as a part of J2SDK to develop Java applications that can communicate with databases.

Chapter 3 DB-Gateways

Databases and JDBC. by Vlad Costel Ungureanu for Learn Stuff

Discuss setting up JDBC connectivity. Demonstrate a JDBC program Discuss and demonstrate methods associated with JDBC connectivity

SQL Environment: Module Types. System Aspects of SQL. SQL Environment: Introduction. SQL Environment: Introduction. SQL Environment: Privileges

JDBC Java Database Connectivity is a Java feature that lets you connect

Java Database Connectivity

Marcin Luckner Warsaw University of Technology Faculty of Mathematics and Information Science

Wentworth Institute of Technology COMP570 Database Applications Fall 2014 Derbinsky. SQL Programming. Lecture 8. SQL Programming

SQL DML and DB Applications, JDBC

These notes add to the JDBC discussion your textbook.

Programming in Java

Non-interactive SQL. EECS Introduction to Database Management Systems

BUSINESS INTELLIGENCE LABORATORY. Data Access: Relational Data Bases. Business Informatics Degree

CHAPTER 2 JDBC FUNDAMENTALS

Java Database Connectivity (JDBC) 25.1 What is JDBC?

Java Database Connectivity

System Aspects of SQL

The Web Application Developer s. Red Hat Database. View. October 30, Webcast. Patrick Macdonald, Fernando Nasser. Red Hat Database Engineering

DataBase Lab JAVA-DATABASE CONNECTION. Eng. Haneen El-masry

PERSİSTENCE OBJECT RELATİON MAPPİNG

SQL and Java. Database Systems Lecture 20 Natasha Alechina

COMP102: Introduction to Databases, 23

CSE 308. Database Issues. Goals. Separate the application code from the database

Database Application Development

Database Explorer Quickstart

Introduction to JDBC. JDBC: Java Database Connectivity. Why Access a Database with Java? Compilation. Six Steps. Packages to Import

WebSphere Connection Pooling. by Deb Erickson Shawn Lauzon Melissa Modjeski

Server-side Web Programming

Database Application Development Part 2 - Chapter

Database Application Development

Transcription:

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.