Sunteți pe pagina 1din 114

JDBC - Java Database Connectivity Tutorials

Java Database Connectivity or in short JDBC is a technology that enables the java program to manipulate data stored into the database. Here is the complete tutorial on JDBC technology. 1. What is JDBC? JDBC is Java application programming interface that allows the Java programmers to access database management system from Java code. It was developed by JavaSoft, a subsidiary of Sun Microsystems. 2. Product Components of JDBC JDBC is consists of four Components: The JDBC API, JDBC Driver Manager, The JDBC Test Suite and JDBC-ODBC Bridge. 3. Understanding JDBC Architecture JDBC is an API specification developed by Sun Microsystems that defines a uniform interface for accessing various relational databases. JDBC is a core part of the Java platform and is included in the standard JDK distribution. 4. JDBC Driver and Its Types The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC architecture. It is quite small and simple. 5. JDBC Versions From First To Latest In this section we have described all the versions of JDBC from first to the latest. 6. Features of JDBC 3.0 In this tutorial we will you know what new features have been added in JDBC 3.0. 7. Features of JDBC 4.0 In this tutorial we will you know what new features have been added in JDBC 3.0. 8. New Features in JDBC 4.0 Java database connectivity (JDBC) is the Java Soft specification of the API. It allows Application Programs to interact with the Database to access the Relational Data. 9. More APIs Become Available More APIs have been added to this version of JDBC to provide access to commonly implemented features of SQL:2003. In addition, several new methods have been added to commonly used interfaces to support easier and better data manipulation. 10. Accessing Database using Java and JDBC Learn how to access database using JDBC.

11. Enhanced SQL Exception Handling A lot of improvement has been done regarding Exception handling in the following fields: 12. Wrapper This new wrapper interface provides a mechanism for accessing an instance of a resource. This is used by many JDBC driver implementations. 13. Difference between JDBC 3.0 And JDBC 4.0 In this tutorial you will know the difference between JDBC 3.0 and JDBC 4.0 14. Relational Database Concepts An important part of every business is to keep records. We need to keep records of our customers, the employees of our company, the emails etc. A Relational model is the basis for any relational database management system (RDBMS). 15. Understanding Common SQL Statements This section describes SELECT, INSERT, UPDATE and DELETE statements. 16. Important JDBC Concepts This section introduces you with Transactions, logging, isolation and concurrency concepts. 17. Introduction to the java.sql Package This package provides the APIs for accessing and processing data which is stored in the database especially relational database by using the java programming language. It includes a framework where we different drivers can be installed dynamically to access different databases especially relational databases. 18. Understanding Driver Manager The main responsibility of JDBC database driver is to load all the drivers found in the system properly as well as to select the most appropriate driver from opening a connection to a database. The Driver Manager also helps to select the most appropriate driver from the previously loaded drivers when a new open database is connected. 19. Understanding Data Source DataSource object can be thought as a factory for making connections to the particular database that the DataSource instance represents. 20. Understanding the Connection Object A Connection object represents a connection with a database with a database. When we connect to a database by using connection method, we create a Connection Object, which represents the connection to the database.

21. JDBC Steps in writing JDBC applications This section gives you brief description of JDBC Steps for making connection with the database, executing the query and showing the data to the user. JDBC Examples with MySQL 1. JDBC MySQL Tutorial JDBC Tutorials with MySQL Database. MySQL is one of the widely used database in the world. 2. Connecting to a MySQL Database in Java In this section, you will learn how to connect the MySQL database with Java file. We need to establish a connection between MySQL and Java files so that we can use MySQL driver for MySQL. 3. Creating a Database Table Here, providing you an example with code and it's description that helps you to create a database table in a database through the java file. 4. Creating a MySQL Database Table to store Java Types Dear user, consider a case where we need to store a java types in our database table. This section describes how to create a MySQL database table that stores all java types. 5. Deleting a Table from Database This section describes how to delete a table from database. Java provide the facility for deleting a specific table from a given database with the help of some specified methods. 6. Retrieving Tables from a Database This section provides you a facility for retrieving tables from a specific database through an example. You have to know about a database that is a collection of data or information. 7. Inserting values in MySQL database table Here we are going to see, how we can insert values in the MySQL database table. We know that tables store data in rows and column format. After creating a database table, you insert the values in it. 8. Retrieving All Rows from a Database Table Here, you will learn how to retrieve all rows from a database table. You know that table contains or stores the data in rows and columns format. If you want to access the data from a table then you need to use some APIs and methods. 9. Getting Column Names from a database table in Java Here, providing you an example with code that retrieves all columns name in a specific database table. Sometimes, you need to know the number of columns and the names of the columns of the table then you can retrieve it with the help of this example. 10. Deleting All Rows from a Database Table Consider a case where we have been given one database table, now we have to delete all the rows from the table. This section describes for deleting all rows from a specific database table.

11. Delete a Specific Row from a Database Table Consider a case where we are creating a table and we have add some data in it. It may happen that we might add a wrong data in a row, now we need to delete that particular data. This can be done very easily , and in this section we are going to do the same that is, how to delete a specific row from a specific database table. 12. Join tables in the specific database In this section, we are going to consider how to join two or more tables in a specific database. For this you need to have two or more table in the database. If two or more tables are available in the database then Join operation is performed otherwise not. 13. Join tables with the NATURAL LEFT JOIN operation This section describes the NATURAL LEFT JOIN operation and how to retrieve data through it. In this operation we are going to retrieve data according to match the field name of another tables. 14. Join tables with the NATURAL RIGHT JOIN operation This section describes the NATURAL RIGHT JOIN operation of table in a specific database. This operation join tables on the basis of matching fields but priority will be given to the right table field values. 15. Cross Join Tables in a Specific Database This section introduces you to the cross join between two tables. The cross join operation retrieves data between two tables as a Cartesian product of set theory in mathematics. All data show to multiply by each rows. JDBC Tutorials 1. JDBC (Java Database Connectivity) -Tutorials JDBC is essentially an Application Programming Interface (API) for executing SQL statements, and extracting the results. Using this API, we can write database clients, such as Java applets, servlets and Enterprise JavaBeans, that connect to a relational database, such as Oracle, MySQL, Sybase, Informix, Ingres, PostgreSQL, or any other database that implements this API, execute SQL statements, and process the results extracted from the database. 2. First Step towards JDBC This article introduce you with JDBC and shows you how to create a database application to access the databases. 3. Accessing the Database from Servlet This article shows you how to access database from servlets. Here I am assuming that you are using win95/98/2000 and running Java Web Server. 4. JDBC Components JDBC stands for Java Database Connectivity. For connectivity with the database we uses JDBC. It establish connection to access the database. This provides a set of classes in the java.sql package for Java applications to communicate with databases.

5. Get Column Count using ResultSet in SQL This example counts the number of columns in a table. The ResultSetMetaData interface can be used to get type and properties information of columns in a ResultSet. 6. Common SQL Commands SQL commands are divided into categories like DML (Data Manipulation language), DDL (Data definition language), TCL (Tranction control language) and DCL (Data control language). 7. Using JOINING Operation in JDBC Whenever we need to select data from two or more tables, we have to perform a join operation. Tables in a database can be related to each other with keys. 8. Using WHERE Clause in JDBC Where clause is used to retrieve the data from a table based on some specific conditions. It allows to filter the data from a table, a WHERE clause can be added to the SELECT statement. 9. Using Select Statements in JDBC The SELECT statement is used to select data from a table. For terminating a statement, semicolon is used. When we want to fetch the data from any table then we have to use SELECT statement. 10. Display Data from Database in JSP This is detailed java program to connect java application with mysql database and execute query to display data from the specified table. 11. Servlet Example To Display Mysql Clob Data A Clob is a Character Large Object in a Database. Clob can be very large depending on the Database up to 4 GB. It is a rich data type of JDBC. A large character data file can be stored as CLOB type. JDBC provides java.sql.Clob interface for handling large character/text object. 12. Servlet Example To Display Mysql Blob Data This example shows you how to use JDBC's rich data type BLOB. The BLOB type stores/retreives large binary objects such as PDF files, video clips, JPEG/GIF pictures, and Microsoft word documents. 13. Servlet Example To Update Mysql Clob Data This example shows how to update CLOB data in the database. In our example, servlet InsertClobExample takes url for the CLOB data (the url will be pointing to a text file). Therefore, we will represent the CLOB as a url. 14. Servlet Example To Delete Mysql Clob Data A Clob is a Character Large Object in a Database. A large character data file upto 4 GB can be stored as CLOB type. JDBC provides java.sql.Clob interface for handling

large character/text object. 15. Servlet Example To Delete Mysql Blob Data BLOB data in SQL is a built-in type used for storing Binary Large Object. The BLOB type stores/retreives large binary objects such as PDF files, video clips, JPEG/GIF pictures, and Microsoft word documents. 16. Servlet Example To Insert Mysql Clob Data This example shows how to insert CLOB data in the database. In our example, servlet InsertClobExample takes url for the CLOB data (the url will be pointing to a text file). Therefore, we will represent the CLOB as a url. 17. GET DATE in JDBC This example shows how to retrieve date from existing table of MySql database. Date functions can be used in the SELECT statement or in the WHERE clause of a Query. 18. Create table and insert data by sql query This is detailed java program to connect java application and execute sql query like create table in mysql database, insert some values and retrieve values from the table. 19. Insert Image into Mysql Database through Simple Java Code This is detailed simple java code that how save image into mysql database. Before running this java code you need to create data base and table to save image in same database. 20. Delete row and column from table through java code In this section we will see how to delete row and column from given table through java code. Java code create connection between program and database by using connection interface and JDBC driver. 21. JDBC ConnectionUrl In this Tutorial we want to describe you a code that helps you to understand JDBC Connection Url.For this we have a class JDBCConnectionUrl,Inside the main method, we declared a variable Connection,Statement,ResultSet. 22. JDBC connection In this Tutorial we want to describe you a code that helps you in understanding a JDBC Connection. 23. JDBC batch JDBC is simply a Java Database Connectivity. This Connectivity provides you an API, that provides you to interact your Java Application in your front end with the backend. 24. JDBC batch insert In this Tutorial we want to describe you a code that helps you in understand JDBC batch

insert. 25. JDBC batch update JDBC Update is used when you want to save all the modify or changes values in a database. 26. JDBC autocommit JDBC connection is said to be auto commit if all the statement in SQL will be committed and executed altogether as a individual transaction. 27. JDBC access database JDBC is a Java Database Connectivity. The JDBC Connectivity provides API classes and interfaces for connecting the front end in Java application with database connections. 28. JDBC connection timeout In this Tutorial we want to describe you a code that help you in understand JDBC connection timeout. 29. JDBC Connectivity Code In Java In this Tutorial we want to describe you a code that helps you in understanding JDBC Connectivity Code in Java. The code include a class JDBC Connectivity Code in Java. 30. JDBC Drive For Mysql In this Tutorial we want to describe you a code that help you in understanding JDBC Drive for Mysql. 31. JDBC Execute Query In this Tutorial we want to explain you an example from JDBC Execute query. 32. JDBC Execute Statement In this Tutorial we want to describe you a code that help you in understand to explain JDBC Execute Statement. 33. JDBC Execute Update Example JDBC Execute Update query is used to modify or return you an integer value specify the number of rows affected in the backend of database. 34. JDBC Fetch In this Tutorial we want to describe you an example from JDBC Fetch. 35. JDBC Functions In this Tutorial we want to describe you a code that helps you easy to understand JDBC Functions. 36. JDBC Get Row Count In this Tutorial we want to describe a code that make you to understand in JDBC Get

Row Count. 37. JDBC Exception In this Tutorial we want to describe you a code that help you to understand JDBC Exception. 38. JDBC Get Column Names In this Tutorial we want to describe you a code that helps you to understand JDBCGetColumn Names. 39. JDBC Get Int In this tutorial we want to describe you a code that help in understanding JDBC Get Int. 40. JDBC Get Connection In this Tutorial we want to describe you a code that help you in understand JDBC GetConnection. 41. JDBC Next In this Tutorial we help you to understand an example from JDBC Next. 42. JDBC Mysql Connection Url The Tutorial want to illustrate a code that explain you to understand JDBC Mysql Connection. The code include a class JdbcMysqlConnectionUrl. 43. JDBC Meta Data Get tables The Tutorial helps you to know an example from JDBC MetaDataGettable. 44. JDBC Insert Statement The Tutorial give you an example from JDBC Insert Statement. 45. JDBC Insert Record In this Tutorial we want to explain you an example from JDBC Insert Record. 46. JDBC Get Metadata The Tutorial illustrate a program that helps you to understand JDBC Get Metadata. 47. JDBC Insert Null In this Tutorial we want to describe you a code that help in understanding JDBC InsertNull. 48. JDBC Insert Preparedstatement In this Tutorial we want to describe you a code that helps you in understanding JDBC Insert Prepared Statement. 49. JDBC-ODBC Connectivity The code illustrates an example from JDBC-ODBC Connectivity. In this Example we

include a class JdbcOdbcConnectivity ,the class include a main method ( ). 50. JDBC-ODBC Connection JDBC-ODBC Connection is a JDBC driver that translates the operation in JDBC into ODBC. For ODBC,it is a normal java application program. This bridge provides JDBC for database in which an ODBC driver is available. 51. JDBC Nested Resultset The JDBC Nested Result Set is the simplest join algorithm. In this case for each tuple in the outer join relation, the entire inner join is scanned and the tuple matches the join condition are finally added to the result set. 52. JDBC Prepared Statement Addbatch The code illustrate an example from JDBC Prepared statement Add batch. In this code we have defined a class Jdbc PreparedstatementAddbatch. 53. JDBC Prepared statement Close The code illustrates you an example from JDBC Prepared Statement Close. In this code, the class Jdbc Preparedstaement Close include a main method. 54. JDBC Prepared Statement Example Prepared Statement is different from Statement object, When it is created ,it is represented as SQL statement. The advantage of this statement is SQL statement sent to the DBMS,in which it is compiled. 55. JDBC Prepared Statement Insert The Tutorial illustrates a program in JDBC Prepared Statement Insert. In this program the code include a class JdbcPreparedstatementInsert. 56. JDBC Prepared Statement Update The Tutorial illustrates a code that help you in understanding JDBC Prepared Statement Update. The code include a class Jdbc Prepared Statement, this class include a main method ( ),

What is JDBC?
JDBC is Java application programming interface that allows the Java programmers to access database management system from Java code. It was developed by JavaSoft, a subsidiary of Sun Microsystems. Definition Java Database Connectivity in short called as JDBC. It is a java API which enables the java programs to execute SQL statements. It is an application programming interface that defines how a java programmer can access the database in tabular format from Java code using a set of standard interfaces and classes written in the Java programming language.

JDBC has been developed under the Java Community Process that allows multiple implementations to exist and be used by the same application. JDBC provides methods for querying and updating the data in Relational Database Management system such as SQL, Oracle etc. The Java application programming interface provides a mechanism for dynamically loading the correct Java packages and drivers and registering them with the JDBC Driver Manager that is used as a connection factory for creating JDBC connections which supports creating and executing statements such as SQL INSERT, UPDATE and DELETE. Driver Manager is the backbone of the jdbc architecture. Generally all Relational Database Management System supports SQL and we all know that Java is platform independent, so JDBC makes it possible to write a single database application that can run on different platforms and interact with different Database Management Systems. Java Database Connectivity is similar to Open Database Connectivity (ODBC) which is used for accessing and managing database, but the difference is that JDBC is designed specifically for Java programs, whereas ODBC is not depended upon any language. In short JDBC helps the programmers to write java applications that manage these three programming activities: 1. It helps us to connect to a data source, like a database. 2. It helps us in sending queries and updating statements to the database and 3. Retrieving and processing the results received from the database in terms of answering to your query.

Product Components of JDBC


JDBC has four Components: 1. The JDBC API. 2. The JDBC Driver Manager. 3. The JDBC Test Suite. 4. The JDBC-ODBC Bridge. 1. The JDBC API. The JDBC application programming interface provides the facility for accessing the relational database from the Java programming language. The API technology provides the industrial standard for independently connecting Java programming language and a wide range of databases. The user not only execute the SQL statements, retrieve results, and update the data but can also access it anywhere within a network because of it's "Write Once, Run Anywhere" (WORA) capabilities.

Due to JDBC API technology, user can also access other tabular data sources like spreadsheets or flat files even in the a heterogeneous environment. JDBC application programmming interface is a part of the Java platform that have included Java Standard Edition (Java SE ) and the Java Enterprise Edition (Java EE) in itself. The JDBC API has four main interface: The latest version of JDBC 4.0 application programming interface is divided into two packages i-) java.sql ii-) javax.sql. Java SE and Java EE platforms are included in both the packages. 2. The JDBC Driver Manager. The JDBC Driver Manager is a very important class that defines objects which connect Java applications to a JDBC driver. Usually Driver Manager is the backbone of the JDBC architecture. It's very simple and small that is used to provide a means of managing the different types of JDBC database driver running on an application. The main responsibility of JDBC database driver is to load all the drivers found in the system properly as well as to select the most appropriate driver from opening a connection to a database. The Driver Manager also helps to select the most appropriate driver from the previously loaded drivers when a new open database is connected. 3. The JDBC Test Suite. The function of JDBC driver test suite is to make ensure that the JDBC drivers will run user's program or not . The test suite of JDBC application program interface is very useful for testing a driver based on JDBC technology during testing period. It ensures the requirement of Java Platform Enterprise Edition (J2EE). 4. The JDBC-ODBC Bridge. The JDBC-ODBC bridge, also known as JDBC type 1 driver is a database driver that utilize the ODBC driver to connect the database. This driver translates JDBC method calls into ODBC function calls. The Bridge implements Jdbc for any database for which an Odbc driver is available. The Bridge is always implemented as the sun.jdbc.odbc Java package and it contains a native library used to access ODBC. Now we can conclude this topic: This first two component of JDBC, the JDBC API and the JDBC Driver Manager manages to connect to the database and then build a java program that utilizes SQL commands to communicate with any RDBMS. On the other hand, the last two components are used to communicate with ODBC or to test web application in the specialized environment.

Understanding the JDBC Architecture


JDBC is an API specification developed by Sun Microsystems that defines a uniform interface for accessing various relational databases. JDBC is a core part of the Java platform and is included in the standard JDK distribution. The primary function of the JDBC API is to provide a means for the developer to issue SQL statements and process the results in a consistent, database-independent manner. JDBC provides rich, object-oriented access to databases by defining classes and interfaces that represent objects such as: 1. Database connections 2. SQL statements 3. Result Set 4. Database metadata 5. Prepared statements 6. Binary Large Objects (BLOBs) 7. Character Large Objects (CLOBs) 8. Callable statements 9. Database drivers 10. Driver manager The JDBC API uses a Driver Manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The Driver Manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. The location of the driver manager with respect to the JDBC drivers and the servlet is shown in Figure 1. Layers of the JDBC Architecture

A JDBC driver translates standard JDBC calls into a network or database protocol or into a database library API call that facilitates communication with the database. This translation layer provides JDBC applications with database independence. If the back-end database changes, only the JDBC driver need be replaced with few code modifications required. There are four distinct types of JDBC drivers. Type 1 JDBC-ODBC Bridge. Type 1 drivers act as a "bridge" between JDBC and another database connectivity mechanism such as ODBC. The JDBC- ODBC bridge provides JDBC access using most standard ODBC drivers. This driver is included in the Java 2 SDK within the sun.jdbc.odbc package. In this driver the java statements are converted to a jdbc statements. JDBC statements calls the ODBC by using the JDBC-ODBC Bridge. And finally the query is executed by the database. This driver has serious limitation for many applications. (See Figure 2.) Type 1 JDBC Architecture

Type 2 Java to Native API. Type 2 drivers use the Java Native Interface (JNI) to make calls

to a local database library API. This driver converts the JDBC calls into a database specific call for databases such as SQL, ORACLE etc. This driver communicates directly with the database server. It requires some native code to connect to the database. Type 2 drivers are usually faster than Type 1 drivers. Like Type 1 drivers, Type 2 drivers require native database client libraries to be installed and configured on the client machine. (See Figure 3.) Type 2 JDBC Architecture

Type 3 Java to Network Protocol Or All- Java Driver. Type 3 drivers are pure Java drivers that use a proprietary network protocol to communicate with JDBC middleware on the server. The middleware then translates the network protocol to database-specific function calls. Type 3 drivers are the most flexible JDBC solution because they do not require native database libraries on the client and can connect to many different databases on the back end. Type 3 drivers can be deployed over the Internet without client installation. (See Figure 4.) Java-------> JDBC statements------> SQL statements ------> databases. Type 3 JDBC Architecture

Type 4 Java to Database Protocol. Type 4 drivers are pure Java drivers that implement a proprietary database protocol (like Oracle's SQL*Net) to communicate directly with the database. Like Type 3 drivers, they do not require native database libraries and can be deployed over the Internet without client installation. One drawback to Type 4 drivers is that they are database specific. Unlike Type 3 drivers, if your back-end database changes, you may save to purchase and deploy a new Type 4 driver (some Type 4 drivers are available free of charge from the database manufacturer). However, because Type drivers communicate directly with the database engine rather than through middleware or a native library, they are usually the fastest JDBC drivers available. This driver directly converts the java statements to SQL statements. (See Figure 5.) Type 4 JDBC Architecture

So, you may be asking yourself, "Which is the right type of driver for your application?" Well, that depends on the requirements of your particular project. If you do not have the opportunity or inclination to install and configure software on each client, you can rule out Type 1 and Type 2 drivers.

However, if the cost of Type 3 or Type 4 drivers is prohibitive, Type 1 and type 2 drivers may become more attractive because they are usually available free of charge. Price aside, the debate will often boil down to whether to use Type 3 or Type 4 driver for a particular application. In this case, you may need to weigh the benefits of flexibility and interoperability against performance. Type 3 drivers offer your application the ability to transparently access different types of databases, while Type 4 drivers usually exhibit better performance and, like Type 1 and Type 2 drivers, may be available free if charge from the database manufacturer.

JDBC Driver and Its Types


JDBC Driver Manager The JDBC DriverManager class defines objects which can connect Java applications to a JDBC driver. DriverManager has traditionally been the backbone of the JDBC architecture. It is quite small and simple. This is a very important class. Its main purpose is to provide a means of managing the different types of JDBC database driver. On running an application, it is the DriverManager's responsibility to load all the drivers found in the system property jdbc. drivers. For example, this is where the driver for the Oracle database may be defined. This is not to say that a new driver cannot be explicitly stated in a program at runtime which is not included in jdbc.drivers. When opening a connection to a database it is the DriverManager' s role to choose the most appropriate driver from the previously loaded drivers. The JDBC API defines the Java interfaces and classes that programmers use to connect to databases and send queries. A JDBC driver implements these interfaces and classes for a particular DBMS vendor. A Java program that uses the JDBC API loads the specified driver for a particular DBMS before it actually connects to a database. The JDBC DriverManager class then sends all JDBC API calls to the loaded driver. JDBC Driver This topic defines the Java(TM) Database Connectivity (JDBC) driver types. Driver types are used to categorize the technology used to connect to the database. A JDBC driver vendor uses these types to describe how their product operates. Some JDBC driver types are better suited for some applications than others. Types of JDBC drivers This topic defines the Java(TM) Database Connectivity (JDBC) driver types. Driver types are used to categorize the technology used to connect to the database. A JDBC driver vendor uses these types to describe how their product operates. Some JDBC driver types are better suited for

some applications than others. There are four types of JDBC drivers known as:
y y y y

JDBC-ODBC bridge plus ODBC driver, also called Type 1. Native-API, partly Java driver, also called Type 2. JDBC-Net, pure Java driver, also called Type 3. Native-protocol, pure Java driver, also called Type 4.

Type 1 Driver- the JDBC-ODBC bridge The JDBC type 1 driver, also known as the JDBC-ODBC bridge is a database driver implementation that employs the ODBC driver to connect to the database. The driver converts JDBC method calls into ODBC function calls. The bridge is usually used when there is no pureJava driver available for a particular database. The driver is implemented in the sun.jdbc.odbc.JdbcOdbcDriver class and comes with the Java 2 SDK, Standard Edition. The driver is platform-dependent as it makes use of ODBC which in turn depends on native libraries of the operating system. Also, using this driver has got other dependencies such as ODBC must be installed on the computer having the driver and the database which is being connected to must support an ODBC driver. Hence the use of this driver is discouraged if the alternative of a pure-Java driver is available. Type 1 is the simplest of all but platform specific i.e only to Microsoft platform. A JDBC-ODBC bridge provides JDBC API access via one or more ODBC drivers. Note that some ODBC native code and in many cases native database client code must be loaded on each client machine that uses this type of driver. Hence, this kind of driver is generally most appropriate when automatic installation and downloading of a Java technology application is not important. For information on the JDBC-ODBC bridge driver provided by Sun, see JDBCODBC Bridge Driver. Type 1 drivers are "bridge" drivers. They use another technology such as Open Database Connectivity (ODBC) to communicate with a database. This is an advantage because ODBC drivers exist for many Relational Database Management System (RDBMS) platforms. The Java Native Interface (JNI) is used to call ODBC functions from the JDBC driver. A Type 1 driver needs to have the bridge driver installed and configured before JDBC can be used with it. This can be a serious drawback for a production application. Type 1 drivers cannot be used in an applet since applets cannot load native code. Functions: 1. Translates query obtained by JDBC into corresponding ODBC query, which is then handled by the ODBC driver.

Sun provides a JDBC-ODBC Bridge driver. sun.jdbc.odbc.JdbcOdbcDriver. This driver is native code and not Java, and is closed source. 3. Client -> JDBC Driver -> ODBC Driver -> Database 4. There is some overhead associated with the translation work to go from JDBC to ODBC. Advantages: Almost any database for which ODBC driver is installed, can be accessed. Disadvantages: 1. Performance overhead since the calls have to go through the JDBC overhead bridge to the ODBC driver, then to the native database connectivity interface. 2. The ODBC driver needs to be installed on the client machine. 3. Considering the client-side software needed, this might not be suitable for applets. Type 2 Driver - the Native-API Driver The JDBC type 2 driver, also known as the Native-API driver is a database driver implementation that uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. The type 2 driver is not written entirely in Java as it interfaces with non-Java code that makes the final database calls. The driver is compiled for use with the particular operating system. For platform interoperability, the Type 4 driver, being a full-Java implementation, is preferred over this driver. A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS. Note that, like the bridge driver, this style of driver requires that some binary code be loaded on each client machine. However the type 2 driver provides more functionality and performance than the type 1 driver as it does not have the overhead of the additional ODBC function calls. Type 2 drivers use a native API to communicate with a database system. Java native methods are used to invoke the API functions that perform database operations. Type 2 drivers are generally faster than Type 1 drivers. Type 2 drivers need native binary code installed and configured to work. A Type 2 driver also uses the JNI. You cannot use a Type 2 driver in an applet since applets cannot load native code. A Type 2 JDBC driver may require some Database Management System (DBMS) networking software to be installed. The Developer Kit for Java JDBC driver is a Type 2 JDBC driver.

2.

Functions: 1. This type of driver converts JDBC calls into calls to the client API for that database. 2. Client -> JDBC Driver -> Vendor Client DB Library -> Database Advantage Better performance than Type 1 since no jdbc to odbc translation is needed. Disadvantages 1. The vendor client library needs to be installed on the client machine. 2. Cannot be used in internet due the client side software needed. 3. Not all databases give the client side library. Type 3 driver - the Network-Protocol Driver The JDBC type 3 driver, also known as the network-protocol driver is a database driver implementation which makes use of a middle-tier between the calling program and the database. The middle-tier (application server) converts JDBC calls directly or indirectly into the vendorspecific database protocol. This differs from the type 4 driver in that the protocol conversion logic resides not at the client, but in the middle-tier. However, like type 4 drivers, the type 3 driver is written entirely in Java. The same driver can be used for multiple databases. It depends on the number of databases the middleware has been configured to support. The type 3 driver is platform-independent as the platform-related differences are taken care by the middleware. Also, making use of the middleware provides additional advantages of security and firewall access. A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMSindependent net protocol which is then translated to a DBMS protocol by a server. This net server middleware is able to connect all of its Java technology-based clients to many different databases. The specific protocol used depends on the vendor. In general, this is the most flexible JDBC API alternative. It is likely that all vendors of this solution will provide products suitable for Intranet use. In order for these products to also support Internet access they must handle the additional requirements for security, access through firewalls, etc., that the Web imposes. Several vendors are adding JDBC technology-based drivers to their existing database middleware products. These drivers use a networking protocol and middleware to communicate with a server. The server then translates the protocol to DBMS function calls specific to DBMS. Type 3 JDBC drivers are the most flexible JDBC solution because they do not require any native binary code on the client. A Type 3 driver does not need any client installation.

Functions: 1. Follows a three tier communication approach. 2. Can interface to multiple databases - Not vendor specific. 3. The JDBC Client driver written in java, communicates with a middleware-net-server using a database independent protocol, and then this net server translates this request into database commands for that database. 4. Thus the client driver to middleware communication is database independent. 5. Client -> JDBC Driver -> Middleware-Net Server -> Any Database Advantages 1. Since the communication between client and the middleware server is database independent, there is no need for the vendor db library on the client machine. Also the client to middleware need'nt be changed for a new database. 2. The Middleware Server (Can be a full fledged J2EE Application server) can provide typical middleware services like caching (connections, query results, and so on), load balancing, logging, auditing etc.. 3. eg. for the above include jdbc driver features in Weblogic. 4. Can be used in internet since there is no client side software needed. 5. At client side a single driver can handle any database.(It works provided the middlware supports that database!!) Disadvantages 1. Requires database-specific coding to be done in the middle tier. 2. An extra layer added may result in a time-bottleneck. But typically this is overcome by providing efficient middleware services described above. Type 4 - the Native-Protocol Driver The JDBC type 4 driver, also known as the native-protocol driver is a database driver implementation that converts JDBC calls directly into the vendor-specific database protocol. The type 4 driver is written completely in Java and is hence platform independent. It is installed inside the Java Virtual Machine of the client. It provides better performance over the type 1 and 2 drivers as it does not have the overhead of conversion of calls into ODBC or database API calls. Unlike the type 1 and 2 drivers, it does not need associated software to work. A native-protocol fully Java technology-enabled driver converts JDBC technology calls into the network protocol used by DBMSs directly. This allows a direct call from the client machine to the DBMS server and is a practical solution for Intranet access. Since many of these protocols are proprietary the database vendors themselves will be the primary source for this style of driver. Several database vendors have these in progress.

As the database protocol is vendor-specific, separate drivers, usually vendor-supplied, need to be used to connect to the database. A Type 4 driver uses Java to implement a DBMS vendor networking protocol. Since the protocols are usually proprietary, DBMS vendors are generally the only companies providing a Type 4 JDBC driver. Type 4 drivers are all Java drivers. This means that there is no client installation or configuration. However, a Type 4 driver may not be suitable for some applications if the underlying protocol does not handle issues such as security and network connectivity well. The IBM Toolbox for Java JDBC driver is a Type 4 JDBC driver, indicating that the API is a pure Java networking protocol driver. Functions 1. Type 4 drivers are entirely written in Java that communicate directly with a vendor's database through socket connections. No translation or middleware layers, are required, improving performance. 2. The driver converts JDBC calls into the vendor-specific database protocol so that client applications can communicate directly with the database server. 3. Completely implemented in Java to achieve platform independence. 4. e.g include the widely used Oracle thin driver - oracle.jdbc.driver. OracleDriver which connect to jdbc:oracle:thin URL format. 5. Client Machine -> Native protocol JDBC Driver -> Database server Advantages These drivers don't translate the requests into db request to ODBC or pass it to client api for the db, nor do they need a middleware layer for request indirection. Thus the performance is considerably improved. Disadvantage At client side, a separate driver is needed for each database.

JDBC Versions
1). The JDBC 1.0 API. 2). The JDBC 1.2 API. 3). The JDBC 2.0 Optional Package API.

4). The JDBC 2.1 core API. 5) The JDBC 3.0 API. 6) The JDBC 4.0 API. Features of JDBC 1.0 API The JDBC 1.0 API was the first officially JDBC API launched consists of the following java classes and interfaces that you can open connections to particular databases. This version includes a completely redesigned administration console with an enhanced graphical interface to manage and monitor distributed virtual databases. Features of JDBC 1.2 API 1). It supports Updatabale ResultSets. 2). The DatabaseMetaData code has been refactored to provide more transparency with regard to the underlying database engine. 3) New pass through schedulers for increased performance.

Features of The JDBC 2.0 Optional Pacakage API 1). The use of DataSource interface for making a connection. 2). Use of JNDI to specify and obtain database connections. 3). It allows us to use Pooled connections, that is we can reuse the connections. 4). In this version the distrbuted transactions is possible. 5). It provides a way of handling and passing data using Rowset technology. Features of the JDBC 2.1 core API. 1). Scroll forward and backward in a result set or has the ability to move to a specific row. 2). Instead of using SQL commands, we can make updates to a database tables using methods in the Java programming language 3). We can use multiple SQL statements in a a database as a unit, or batch.

4). It uses the SQL3 datatypes as column values. SQL3 types are Blob, Clob, Array, Structured type, Ref. 5). Increased support for storing persistent objects in the java programming language. 6). Supports for time zones in Date, Time, and Timestamp values. 7). Full precision for java.math.BigDecimal values. Features of JDBC 3.0 API 1). Reusabilty of prepared statements by connection pools. 2). In this version there is number of properties defined for the ConnectionPoolDataSource. These properties can be used to describe how the PooledConnection objects created by DataSource objects should be pooled. 3) A new concept has been added to this API is of savepoints. 4). Retrieval of parameter metadata. 5). It has added a means of retrieving values from columns containing automatically generated values. 6). Added a new data type i.e. java.sql.BOOLEAN. 7). Passing parameters to CallableStatement. 8). The data in the Blob and Clob can be altered. 9). DatabaseMetaData API has been added. Features of JDBC 4.0 : 1). Auto- loading of JDBC driver class. 2). Connection management enhancements. 3.) Support for RowId SAL type. 4). SQL exception handling enhancements. 5). DataSet implementation of SQl using Annotations. 6). SQL XML support

Features of JDBC 3.0 API


y Reusabilty of prepared statements by connection pools. y In this version there is number of properties defined for the ConnectionPoolDataSource. These properties can be used to describe how the PooledConnection objects created by DataSource objects should be pooled. y A new concept has been added to this API is of savepoints: One of the useful new features is transactional savepoints. With JDBC 3.0, the transactional model is now more flexible. Now you can start a transaction , insert several rows in it and then create a savepoint. This savepoint serves as a bookmark. The application can rollback to the savepoint and then commit the group of inserts as if the updates have never been attempted. For eg: Statement st=connection.createStatement(); int rowcount=st.executeUpdate("insert into employee values("tim")); int rowcoutn=st.executeUpdate("insert into salary values(20000.0); Savepoint sv=connection.setSavePoint("savepoint"); //create save point for inserts int rowcount=st.executeUpdate("delete from employee"); connection.rollback(sv); //discard the delete statement but keeps the inserts connection.commit(); //inserts are now permanent y Retrieval of parameter metadata. y It has added a means of retrieving values from columns containing automatically generated values. y Added a new data type i.e. java.sql.BOOLEAN. y Passing parameters to CallableStatement. y The data in the Blob and Clob can be altered: JDBC 3.0 introduces a standard mechanism for updating BLOB and CLOB data. y DatabaseMetaData API has been added. y It allows stored procedure parameters to be called by name.

Features of JDBC 4.0


JDBC 4 is a major new release with a strong focus ease-of-use and programmer productivity. JDBC 4's key priority is to make it easier for developers to work directly with the JDBC API. The new features availble in J2SE 1.5 added ease-of-development features in JDBC 4 In addition to ease-of-use, JDBC 4 introduces several SQL 203 features, like Java specific mapping for the new XML SQL type. Now in JDBC 4 every PreparedStatement is poolable by default. 1. Auto- loading of JDBC driver class: In JDBC 4 invoking the getConnection() on DriverManager will automatically load a driver. Upon loading the driver, an instance of the driver is created and the registerDriver() method is invoked to make that driver available to clients.

2. Connection management enhancements: In jdbc it may happen that a Connection is lying idle or not closed in a pool, then it became stale over time. This will led to the connection pool run out of resources due to stale connection. We know that the stale connection doesn't mean that a connection is closed. Now in JDBC 4 Connection class we have provided one method isValid(), which allows a client to query the database driver if a connection is still valid. As database is a shared resource, so many application can access the same data store. To maintain all the records of the client is a difficult task, now in JDBC 4 an application can associate metadata with a database connection via the setClientInfo() method, which takes a name/value pair, or a Properties object. 3. Support for RowId data type: JDBC introduces support for ROWID, a data type that had been in use in database products even before it became part of the SQL. 4. SQL exception handling enhancements: JDBC 4 addresses the error handling beautifully. As databases are often remotely accessible resources, problems such as network failures is common and it can cause exceptions when executing a database operation. SQL statements can also cause exceptions. Prior to JDBC 4, most JDBC operations generated a simple SQLException. 5. SQL XML support: 6. DataSet implementation of SQL using Annotations: The JDBC 4.0 specification leverages annotations to allow developers to associate a SQL query with a Java class without a need to write a lot of code to achieve this association.

New Features in JDBC 4.0


Introduction Java database connectivity (JDBC) is the Java Soft specification of the API. It allows Application Programs to interact with the Database to access the Relational Data. Typically the JDBC API consists of a set of interfaces and classes written in the Java programming language. The applications can be written to connect to databases using these standard interfaces and classes and also to process the results by sending queries written in SQL. Furthermore the backend Database session can be connected by JDBC API which can execute the Queries to get the Results. Some of the new set of features which come along with Mustang is JDBC 4.0 are: 1. 2. 3. 4. 5. No need for Class.forName("DriverName") Changes in Connection and Statement Interface Better Pools Using ResultSet Becomes More Flexible More APIs Become Available

The three most important features of Driver and Connection Management in JDBC are described below with some new features and enhancements. 1. Getting Connected Becomes Easier

This is one of the most important feature in JDBC that has relieved the developers from loading the driver explicitly. Exactly, you got it right, no need to explicitly load the driver by calling Class.forName anymore. So from now on don't bother to load the driver because the DriverManager will automatically load the driver found in the application CLASSPATH while your application tries to connect the database for the first time. However it is still preferred to create an appropriate DataSource object to retrieve a connection. Since the properties of data source instance can be modified which allows portability and transparency, there is no need to modify any application code to connect to a different database instance. Hence to retrieve a connection there is no need to change any application code to connect to a different database instance that requires loading a different driver. For example: Earlier the programmers used to manually load the drivers before making any Database Calls. The code which was used by the programmers is: Class.forName("FullyQualifiedNameOfTheDriverClass"); The disadvantage is that the code will be changed if the Database Driver vendor wants to change the class name. Now this problem doesn't persist anymore. With the help of Service Provider Mechanism available from Java 5, the Driver will be Loaded Automatically by the JVM provided that the Jar files corresponding to the Driver Class are in the appropriate class path. To understand this mechanism consider two entities, one is the service which contains a set of interfaces and the other entity is the provider who gives a well-defined Implementation for the Service. Now to maintain a directory structure, this service is packaged as a Jar by the provider. The structure of a directory is: \\META-INF\\services\\FullNameOfTheService After maintaining the directory structure, if the JDBC Driver Provider wants to make his implementation as a Service then he has to maintain the file name along with the directory structure as, \\META-INF\\services\\java.sql.Driver Rememeber the file should only contain one entry that is the Name of the Provider Class. The function of this entry is to implement the Driver. Also the name of the file is java.sql.Driver in the above code. For instance the content of the file in My SQL would be, File - Java.sql.Driver com.mysql.jdbc.Driver # Class name of the Driver Hence any Java program will automatically load the JDBC driver by the procedure. Moreover if the application class-path contains multiple drivers then the preference will be given to the first matching driver only ignoring the rest of the drivers. 2. Using ResultSet Becomes More Flexible

Several important features of ResultSet interfaces hierarchy are described below: 1. The ResultSet provided by the RowSet sub-interface is scrollable, updateable, and offline-editable . The JDBC programming has become much more easier and flexible due to the current version's support for the SQLXML data type along with these features. 2. Another feature of the ResultSet is the WebRowSet sub-interface. This interface provides the ability to read data from database tables. Moreover it is used to serialize the data to an XML document, and deserialize from XML back to result set.

More APIs Become Available


3. More APIs Become Available: Some APIs and new methods have been added in JDBC 6.0. More APIs have been added to this version of JDBC to provide access to commonly implemented features of SQL:2003. In addition, several new methods have been added to commonly used interfaces to support easier and better data manipulation. Now, let's review some working code and discuss the result of the Example1 class below. It will connect to an embedded Apache Derby database and display the query results in the console. Although JDBC 4.0 has been out for several months now, I found Apache Derby is the only database to provide a driver that even partially supports the JDBC 4.0 specification at the time of this writing (March 2007). All examples in this article are developed using JDK 1.6 and Apache Derby database version 10.2.2.0. For all code examples, I will show only snippets of the actual Java source file that are relevant to the discussion. See the Resources section for complete sample code discussed in this article. EXAMPLE:

4. Changes in Connection and Statement Interface: Some new features have been added to the Connection interface. However, first of all lets see the methods which are already in use to check whether a Connection object is still valid/active or not. int tenSeconds = 10; Connection.isValid(tenSeconds); In the above code the argument that specifies the time duration taken by the API to check whether the Connection is valid or not is Connection.isValid(int) that is Connection.isValid(tenSeconds);. This argument is the Timeout value. The value false will be returned if the timeout interval exceeds. And if the value returned is 0 for the time-out interval

that indicates an Infinite Time-out Duration. Moreover the methods which are used for populating and retrieving the Client Information about a particular driver are: Connection.getClientInfo() Connection.setClientInfo(Properties) methods also the methods which are used to retrieve the Client information individually are: Connection.setClientInfo(String,String) Connection.getClientInfo(String) Now lets see the methods which have been added to the Statement interface. 1. Statement.isClosed() - If the Statement Object is closed it will return true by calling the Statement.close() method. 2. Statement.setPoolable(boolean) - The call to Statement.setPoolable(true) will only act as a request to the Implementation to pool this Statement Object for better performance. 3. Statement.isPoolable() - By default, only PreparedStatement and CallableStatement are pooled by the Implementation. Not all the implementations may support this feature and hence Applications should not depend on this feature always.

Accessing Database using Java and JDBC


Accessing Database using Java and JDBC

Database plays an important role in storing large amount of data in a pattern. Here we are going develop and example to access the database using Java and JDBC. For this, firstly we need to establish a connection between database and java file with the help of various types of APIs, interfaces and methods. We are using MySQL database. Connection: This interface specifies connection with specific databases like: MySQL, MsAccess, Oracle etc and java files. The SQL statements are executed within the context of this interface. Class.forName(String driver): It loads the driver. DriverManager: This class controls a set of JDBC drivers. Each driver has to be register with this class. getConnection(String url, String userName, String password): This method establishes a connection to specified database url. It is having three arguments: url: - Database url where stored or created your database username: - User name of MySQL password: -Password of MySQL

getMetaData(): This is a method of Connection interface. It retrieves the metadata of the database. DataBaseMetaData: This interface gives information about the database like number of tables in the database, columns of the table etc. getTables(null, null, "%", null): This method provides the description of the tables available in the given catalog. As we have set other parameters null, so it will provide only table names. Here is the code:
import java.sql.*; public class AccessDatabases { public static void main(String[] args) { try { Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/test", "root", "root"); Statement st = con.createStatement(); DatabaseMetaData meta = con.getMetaData(); ResultSet rs = meta.getTables(null, null, "%", null); String tableNames = ""; while (rs.next()) { tableNames = rs.getString(3); System.out.println(tableNames); } } catch (Exception e) { } } }

In this section we studies how to connect to database and then list all the tables in the database. We have used MySQL database server.

Enhanced SQL Exception Handling


5. Enhanced SQL Exception Handling: A lot of improvement has been done regarding Exception handling in the following fields: 1. Iterable SQL Exception 2. Concreate Sub Classes for specific SQL Exception Iterable SQL Exception

A new interface which is implemented by the java.sql.SQLException is Iterable<Throwable> interface. To get the Next Set of Exceptions, this interface (Iterable<Throwable> interface) can be iterated further. Not only this it can also be used in Enhanced For-Loops (available from Java 5.0). For example: try{ // Some Database Access Code }catch(SQLException exception){ for(Throwable throwable: exception){ System.out.println(throwable.getMessage()); } } However earlier to get the next Exception the JDBC 4.0 applications used to rely on SQLException.getNextException(). Unlike Iterable SQL Exception, the SQLException.getNextException() used to loop over until it gets the null as a returned exception. try{ // Some Database Access Code }catch(SQLException exception){ System.out.println(exception.getMessage()); SQLException nextException = exception.getNextException(); while (nextException != null){ System.out.println(nextException.getMessage()); nextException = nextException.getNextException(); } } Concreate Sub Class for specific SQL Exception Another feature which is added to Java 6.0 is Sub Class for specific SQL Exception. Few SQL Exception related Sub-Classes have been added to the API. These Exceptions which encapsulate the State of the SQL Error are divided into three groups namely Transient, Recoverable and Non-Transient which are described below.

Transient Exception: It is a kind of exception in which the program recovers from the exception without altering the application. For example, during the program run-time any type of SQL Exception occurs and if in another attempt the program recovers from the same exception then this kind of exception is known as Transient Exception. The java.sql.TransientException class represents this exception. In JDBC 4.0 API following are the identified Transient Exceptions. 1. SQLTransientConnectionException 2. SQLTimeoutException 3. SQLTransactionRollbackException Recoverable Exception: This exception is represented by java.sql.SQLRecoverableException. It is a bit different from the Transient Exception in the sense that this exception can be recovered by applying some Application Specific Recovery. Non-Transient Exception: This exception is represented by java.sql.TransientException. This exception signifies that no matter how many times the application Program tries to recover the exception, it can never be recovered. The exceptions which belong to this group are: 1. 2. 3. 4. 5. 6. SQLFeatureNotSupportedException SQLNonTransientConnectionException SQLDataException SQLInvalidAuthorizationSpecException SQLSyntaxErrorException SQLIntegrityConstraintViolationException

6. Support for SQL RowId A Row Id is an unique Identifier which is supported by databases such as Oracle and DB2. It is used to identify a Row. For instance, there are multiple records without having a unique identifier column then to store the query output in a Collection (such Hashtable) that doesn't allow duplicates ............................................................ The following piece of code shows how to retrieve the value of the Row Id for a particular Row. String selectQuery = " select rowid from Employees where id ='123' "; ResultSet resultSet = statement.executeQuery("selectQuery"); java.sql.Rowid rowId = resultSet.getRowId(); The RowID interface was added to JDBC 4.0 to support the ROWID data type which is supported by databases such as Oracle and DB2. RowId is useful in cases where there are multiple records that don't have a unique identifier column and you need to store the query output in a Collection (such Hashtable) that doesn't allow duplicates. We can use ResultSet's getRowId() method to get a RowId and PreparedStatement's setRowId() method to use the RowId in a query.

An important thing to remember about the RowId object is that its value is not portable between data sources and should be considered as specific to the data source when using the set or update methods in PreparedStatement and ResultSet respectively. So, it shouldn't be shared between different Connection and ResultSet objects Most of the popular Databases support the concept of a Row Id. A Row Id is an unique Identifier which is used to identify a Row. Support for Retrieving and setting the Row Id for a row is made available from JDBC 4.0 version. For example, consider the following piece of code, which will retrieve the value of the Row Id for a particular Row. String selectQuery = " select rowid from Employees where id ='123' "; ResultSet resultSet = statement.executeQuery("selectQuery"); java.sql.Rowid rowId = resultSet.getRowId(); The Row Id is represented by java.sql.RowId class. Before doing any kind of manipulation on the Row Id, it is wise to check whether the under-lying Database implementation provides Support for Row Id(s), as well as the Lifetime of the Row Id objects. The life-time of the Row Id determines how long the Row Id is valid, whether the Row Id exists only for a particular Session or for a Set of Transactions within a Session or Outside the Database Session etc. This availability can be known with the help of DatabaseMetaData like the following, RowIdLifeTime rowIdLifeTime = DatabaseMetaData.getRowIdLifetime(); if (rowIdLifeTime != ROWID_UNSUPPORTED){ // Row Id support is there for this Data source. } The returned RowIdLifeTime is an Enum which tells about the Life-Time of the Row Id object. Possible values are ROWID_UNSUPPORTED, ROWID_VALID_FOREVER, ROWID_VALID_OTHER, ROWID_VALID_SESSION, ROWID_VALID_TRANSACTION and ROWID_VALID_FOREVER.

Wrapper
7.Wrapper This new wrapper interface provides a mechanism for accessing an instance of a resource. This is used by many JDBC driver implementations. Earlier the wrapper used to be data source specific however now the developers can access these resources that are wrapped as proxy class instances. The interface which the developers can use are as follows: This interface describes a standard mechanism to access these wrapped resources represented by their proxy, to permit direct access to the resource delegates. isWrapperFor(Class<?> iface):

Returns true if this either implements the interface argument or is directly or indirectly a wrapper for an object that does. Returns false otherwise. If this implements the interface then return true, else if this is a wrapper then return the result of recursively calling isWrapperFor on the wrapped object. If this does not implement the interface and is not a wrapper, return false. This method should be implemented as a low-cost operation compared to unwrap so that callers can use this method to avoid expensive unwrap calls that may fail. If this method returns true then calling unwrap with the same argument should succeed. unwrap(Class<T> iface): Returns an object that implements the given interface to allow access to non-standard methods, or standard methods not exposed by the proxy. If the receiver implements the interface then the result is the receiver or a proxy for the receiver. If the receiver is a wrapper and the wrapped object implements the interface then the result is the wrapped object or a proxy for the wrapped object. Otherwise return the the result of calling unwrap recursively on the wrapped object or a proxy for that result. If the receiver is not a wrapper and does not implement the interface, then an SQLException is thrown Conclusion We have described some of the new features of Java 6.0 in this section. The enhancement in the features like Automatic Driver Loading, SQL Exception Handling, Changes in Connection and Statement Interface are of great help. All the features have been explained with the help of examples to grasp the things more easily and quickly.

Difference between JDBC 3.0 & JDBC 4.0


Features of JDBC 3.0 1. Reusabilty of prepared statements by connection pools. 2. In this version there is number of properties defined for the ConnectionPoolDataSource. These properties can be used to describe how the PooledConnection objects created by DataSource objects should be pooled. 3. A new concept has been added to this API is of savepoints: One of the useful new features is transactional savepoints. With JDBC 3.0, the transactional model is now more flexible. Now you can start a transaction , insert several rows in it and then create a savepoint. This savepoint serves as a bookmark. The application can rollback to the savepoint and then commit the group of inserts as if the updates have never been attempted. For eg: Statement st=connection.createStatement(); int rowcount=st.executeUpdate("insert into employee values("tim")); int rowcoutn=st.executeUpdate("insert into salary values(20000.0); Savepoint sv=connection.setSavePoint("savepoint"); //create save point for inserts int rowcount=st.executeUpdate("delete from employee");

connection.rollback(sv); //discard the delete statement but keeps the inserts connection.commit(); //inserts are now permanent 4. Retrieval of parameter metadata. 5. It has added a means of retrieving values from columns containing automatically generated values. 6. Added a new data type i.e. java.sql.BOOLEAN. 7. Passing parameters to CallableStatement. 8. The data in the Blob and Clob can be altered: JDBC 3.0 introduces a standard mechanism for updating BLOB and CLOB data. 9. DatabaseMetaData API has been added. 10. It allows stored procedure parameters to be called by name. Features of JDBC 4 JDBC 4 is a major new release with a strong focus ease-of-use and programmer productivity. JDBC 4's key priority is to make it easier for developers to work directly with the JDBC API. The new features availble in J2SE 1.5 added ease-of-development features in JDBC 4 In addition to ease-of-use, JDBC 4 introduces several SQL 203 features, like Java specific mapping for the new XML SQL type. Now in JDBC 4 every PreparedStatement is poolable by default. 1. Auto- loading of JDBC driver class: In JDBC 4 invoking the getConnection() on DriverManager will automatically load a driver. Upon loading the driver, an instance of the driver is created and the registerDriver() method is invoked to make that driver available to clients. 2. Connection management enhancements: In jdbc it may happen that a Connection is lying idle or not closed in a pool, then it became stale over time. This will led to the connection pool run out of resources due to stale connection. We know that the stale connection doesn't mean that a connection is closed. Now in JDBC 4 Connection class we have provided one method isValid(), which allows a client to query the database driver if a connection is still valid. As database is a shared resource, so many application can access the same data store. To maintain all the records of the client is a difficult task, now in JDBC 4 an application can associate metadata with a database connection via the setClientInfo() method, which takes a name/value pair, or a Properties object. 3. Support for RowId data type: JDBC introduces support for ROWID, a data type that had been in use in database products even before it became part of the SQL. 4. SQL exception handling enhancements: JDBC 4 addresses the error handling beautifully. As databases are often remotely accessible resources, problems such as network failures is common and it can cause exceptions when executing a database operation. SQL statements can also cause exceptions. Prior to JDBC 4, most JDBC operations generated a simple SQLException. 5. SQL XML support: 6. DataSet implementation of SQL using Annotations: The JDBC 4.0 specification leverages annotations to allow developers to associate a SQL query with a Java class without a need to write a lot of code to achieve this association.

7.Relational Database Concepts


An important part of every business is to keep records. We need to keep records of our customers, the employees of our company, the emails etc. To keep all the data indivually is quite difficult and hectic job, because whenever if we need the record of a particular customer or an employee we need to search manually. It takes lot of time and still not reliable. Here comes the concept of databases. What is database? A database is an organized collection of information. A simple example of a database are like your telephone directory, recipe book etc. A Relational model is the basis for any relational database management system (RDBMS). A relational model has mainly three components: 1. A collection of objects or relations,. 2. Operators that act on the objects or relations. 3. Data integrity methods. To design a database we need three things: 1. Table 2. Rows 3. Columns A table is one of the most important ingredient to design the database. It is also known as a relation, is a two dimensional structure used to hold related information. A database consists of one or more tables. A table contains rows : Rows is a collection of instance of one thing, such as the information of one employee. A table contains the columns: Columns contains all the information of a single type. Each column in a table is a category of information referred to as a field. One item of data, such as single phone number of a person is called as a Data Value. ACID Properties: ACID properties are one of the important concept for databases. ACID stands for Atomicity, Consistency, Isolation, and Durability. These properties of a DBMS allow safe sharing of data. Without these properties the inaccuracy in the data will be huge. With the help of the ACID properties the accuracy can be maintained. Normalization:

Normalization is a design technique which helps the to design the relational databases. Normalization is essentially a two step process that puts data into tabular form by removing redundant data from the relational tables. A basic goal of normalization is to create a set of relational tables that are free of redundant data and the data should be consistent. Normalization has been divided into following forms. 1. First Normal Form: A relational table, by definition are in first normal form. All values of the columns are atomic. It means that it contains no repeating values. 2. A relationl table is in second normal form if it is in 1NF and every non- key column is fully dependent upon the primary key. 3. A relational table is in third normal form (3NF) if it is already in 2NF and every non- key column is non transitively dependent upon its primary key. The advantage of having table in 3NF is that it eliminates redundant data which in turn saves space and reduces manipulation anomalies.

Understanding Common SQL statements


The commonly used SQL statements are: 1): Select 2): Insert 3): Update 4): Delete SQL Select statement: The SELECT statement is used to select data from a table. Syntax: Select column_names FROM table_name; The result from a SQL query is stored in a resultset. The SELECT statement has mainly three clauses. 1). Select 2.) From 3). Where The Select specifies the table columns that are retrieved. The From clause tells from where the tables has been accessed. The Where clause specifies which tables are used. The Where clause is optional, if not used then all the table rows will be selected. We can see that we have used semicolon at the end of the select statement. It is used to separate each SQL statement in database systems which helps us to execute more than one SQL statement in the same call to the server.

SQL INSERT Statement: This statement allows you to insert a single or multiple records into the database. We can specify the name of the column in which we want to insert the data. Syntax: Insert into table_name values (value1, value2..); The Insert statement has mainly three clauses. 1). Insert: It specifies which table column has to be inserted in the table. 2). Into : It tells in which the data will be stored. 3). Values: In this we insert the values we have to insert. We can also specify the columns for which we want to insert data. The UPDATE Statement: The Update statement is used to modify the data in the table. Whenever we want to update or delete a row then we use the Update statement. The syntax is : UPDATE table_name Set colunm_name = new_value WHERE column_name = some_name; The Update statement has mainly three clauses. 1). UPDATE: It specifies which table column has to be updated. 2). Set: It sets the column in which the data has to be updated. 3). Where: It tells which tables are used. SQL DELETE Statement: This delete statement is used to delete rows in a table. Systax: DELETE FROM table_name WHERE column_name = some_name; The Delete statement has following clauses. 1). Delete: It specifies which table column has to be deleted. 2). From: It tells from where the Table has been accessed. 3). Where: It tells which tables are used.

Important JDBC Concepts


Transactions: Whenever a connection is created by using the JDBC, then by default it is in auto- commit mode. This means that SQL statement will be automatically committed immediately after it is executed and it is treated as a transaction. But imagine a situation where you want to execute a batch of statements, either they should commit at on go or they should get failed together. For this we need to disable the auto- commit mode by using the method: con.setAutoCommit(false). After setting the auto- commit as false, no SQL statement will be committed until we call the con.commit() method. If there arises any problem while committing then the set of statements will be rollback, without committing. Logging: on the server--->logging--->JDBC. By this we can enable JDBC logging and specify a log file name for the JDBC log. Attributes of Logging: 1) Enable JDBC Logging: It determines whether the server has a JDBC log file. 2) JDBC Log File Name: It is the name of the log file. Isolation: The isolation is needed when there are concurrent transactions. Concurrent transactions are transactions are transactions that occurs at the same time. In isolation one transaction does not interfere with another. For setting the isolation level for a JDBC transaction, use the Connection.setTransaction(int level) method By using the snapshot isolation level we can only see the snapshot of the data locked by other transactions when running from inside the transaction with snapshot isolation level. Some of the transaction level are given below: 1). TRANSACTION_NONE 2). TRANSACTION_READ_UNCOMMITED 3. TRANSACTION_READ_COMMITTED 4. TRANSACTION_REPEATABLE_READ 5. TRANSACTION_SERIALIZABLE

By setting the isolation levels you are having an impact on the performance of the transaction. You can get the existing isolation level with: getTransactionIsolation() method. Concurrency: Database concurrency controls ensure that the transactions occur in an ordered fashion. Concurrency control deals with the issue involved with allowing multiple people simultaneous access to shared entities.

Introduction to java.sql package


This package provides the APIs for accessing and processing data which is stored in the database especially relational database by using the java programming language. It includes a framework where we different drivers can be installed dynamically to access different databases especially relational databases. This java.sql package contains API for the following : 1 Making a connection with a database with the help of DriverManager class a) DriverManager class: It helps to make a connection with the driver. b) SQLPermission class: It provides a permission when the code is running within a Security Manager, such as an applet. It attempts to set up a logging stream through the DriverManager class. c) Driver interface : This interface is mainly used by the DriverManager class for registering and connecting drivers based on JDBC technology. d). DriverPropertyInfo class : This class is generally not used by the general user. 2). Sending SQL Parameters to a database : a). Statement interface: It is used to send basic SQL statements. b). PreparedStatement interface: It is used to send prepared statements or derived SQL statements from the Statement object. c). CallableStatement interface : This interface is used to call database stored procedures. d). Connection interface : It provides methods for creating statements and managing their connections and properties. e). Savepoint : It helps to make the savepoints in a transaction. 3). Updating and retrieving the results of a query: a). ResultSet interface: This object maintains a cursor pointing to its current row of data. The cursor is initially positioned before the first row. The next method of the resultset interface moves the cursor to the next row and it will return false if there are no more rows in the

ResultSet object. By default ResultSet object is not updatable and has a cursor that moves forward only. 4.) Providing Standard mappings for SQL types to classes and interfaces in Java Programming language. a). Array interface: It provides the mapping for SQL Array. b). Blob interface : It provides the mapping for SQL Blob. c). Clob interface: It provides the mapping for SQL Clob. d). Date class: It provides the mapping for SQL Date. e). Ref interface: It provides the mapping for SQL Ref. f). Struct interface: It provides the mapping for SQL Struct. g). Time class: It provides the mapping for SQL Time. h). Timestamp: It provides the mapping for SQL Timestamp. i). Types: It provides the mapping for SQL types. 5). Metadata a). DatabaseMetaData interface: It keeps the data about the data. It provides information about the database. b). ResultSetMetaData: It gives the information about the columns of a ResultSet object. c). ParameterMetaData: It gives the information about the parameters to the PreparedStatement commands. 6). Exceptions a). SQLException: It is thrown by the mehods whenever there is a problem while accessing the data or any other things. b). SQLWarning: This exception is thrown to indicate the warning. c). BatchUpdateException: This exception is thrown to indicate that all commands in a batch update are not executed successfully. d). DataTruncation: It is thrown to indicate that the data may have been truncated. 7). Custom mapping an SQL user- defined type (UDT) to a class in the java programming language. a). SQLData interface: It gives the mapping of a UDT to an intance of this class. b). SQLInput interface: It gives the methods for reading UDT attributes from a stream. c). SQLOutput: It gives the methods for writing UDT attributes back to a stream.

Driver Manager Class


The JDBC Driver Manager The JDBC Driver Manager is a very important class that defines objects which connect Java

applications to a JDBC driver. Usually Driver Manager is the backbone of the JDBC architecture. It's very simple and small that is used to provide a means of managing the different types of JDBC database driver running on an application. The main responsibility of JDBC database driver is to load all the drivers found in the system properly as well as to select the most appropriate driver from opening a connection to a database. The Driver Manager also helps to select the most appropriate driver from the previously loaded drivers when a new open database is connected. The DriverManager class works between the user and the drivers. The task of the DriverManager class is to keep track of the drivers that are available and handles establishing a connection between a database and the appropriate driver. It even keeps track of the driver login time limits and printing of log and tracing messages. This class is mainly useful for the simple application, the most frequently used method of this class is DriverManager.getConnetion(). We can know by the name of the method that this method establishes a connection to a database. The DriverManager class maintains the list of the Driver classes. Each driver has to be get registered in the DriverManager class by calling the method DriverManager.registerDriver(). By calling the Class.forName() method the driver class get automatically loaded. The driver is loaded by calling the Class.forName() method. JDBC drivers are designed to tell the DriverManager about themselves automatically when their driver implementation class get loads. This class has many methods. Some of the commonly used methods are given below: 1. deregisterDriver(Driver driver) : It drops the driver from the list of drivers registered in the DriverManager class. 2. registerDriver(Driver driver) : It registers the driver with the DriverManager class. 3. getConnection(String url) : It tries to establish the connection to a given database URL. 4. getConnection(String url, Sting user, String password) : It tries to establish the connection to a given database URL. 5. getConnection(String url, Properties info) : It tries to establish the connection to a given database URL. 6. getDriver(String url) : It attempts to locate the driver by the given string. 7. getDrivers() : It retrieves the enumeration of the drivers which has been registered with the DriverManager class.

Understanding Data Source


The JDBC API provides the DataSource interface as an alternative to the DriverManager for establishing the connection. A DataSource object is the representation of database or the data source in the Java programming language. DataSouce object is mostly preferred over the DriverManager for establishing a connection to the database. DataSource object can be thought as a factory for making connections to the particular database that the DataSource instance represents.

DataSource has a set of properties that identify and describe the real world data source that it represents. The properties include information about the location of the database server, the network protocol use to communicate with the server the name of the database and so on. DataSource object works with JNDI (Java Naming and Directory interface) naming service so application can use the JNDI API to access the DataSource object. In short we can say that the DataSource interface is implemented to provide three kinds of connections: 1). Basic DataSource class This class is provided by the driver vendor. It is used for portability and easy maintence. 2). To provide connection pooling. It is provided by the application server vendor or driver vendor. It works with ConnectionPoolDataSource class provided by a driver vendor. Its advantage is portability, easy maintenence and increased performance. 3). To provide distributed transactions This class works with an XADataSource class, which is provided by the driver vendor. Its advantages are easy maintenence, portability and ability to participate in distributed transactions.
A Connection object represents a connection with a database. When we connect to a database by using connection method, we create a Connection Object, which represents the connection to the database.

Understanding Connection Object


A Connection object represents a connection with a database. When we connect to a database by using connection method, we create a Connection Object, which represents the connection to the database. An application may have one or more than one connections with a single database or many connections with the different databases also. We can use the Connection object for the following things: 1). It creates the Statement, PreparedStatement and CallableStatement objects for executing the SQL statements. 2). It helps us to Commit or roll back a jdbc transactionn. 3). If you want to know about the database or data source to which you are connected then the Connection object gathers information about the database or data source by the use of DatabaseMetaData.

4). It helps us to close the data source. The Connection.isClosed() method returns true only if the Connection.close() has been called. This method is used to close all the connection. Firstly we need to to establish the connection with the database. This is done by using the method DriverManager.getConnection(). This method takes a string containing a URL. The DriverManager class, attempts to locate a driver that can connect to the database represented by the string URL. Whenever the getConnection() method is called the DriverManager class checks the list of all registered Driver classes that can connect to the database specified in the URL. Syntax: String url = "jdbc: odbc: makeConnection"; Connection con = DriverManager.getConnection(url, "userID", "password");
This section gives you brief description of JDBC Steps for making connection with the database, executing the query and showing the data to the user. In this application we have connected to the MySQL database and retrieved the employee names from the dat

JDBC Steps Basic steps in writing a JDBC Application


This section gives you brief description of JDBC Steps for making connection with the database, executing the query and showing the data to the user. In this application we have connected to the MySQL database and retrieved the employee names from the database. Here are the JDBC Steps to be followed while writing JDBC program:
y y y y y

Loading Driver Establishing Connection Executing Statements Getting Results Closing Database Connection

Before explaining you the JDBC Steps for making connection to the database and retrieving the employee from the tables, we will provide you the structure of the database and sample data. Here is the sql script to create table and populate the table with data: -- Table structure for table `employee` CREATE TABLE `employee` ( `employee_name` varchar(50) NOT NULL, PRIMARY KEY (`employee_name`)

); INSERT INTO `employee` (`employee_name`) VALUES ('Deepak Kumar'), ('Harish Joshi'), ('Rinku roy'), ('Vinod Kumar'); Data inserting in MySQL database table: mysql> insert into employee values('Deepak Kumar'); Query OK, 1 row affected (0.24 sec) mysql> insert into employee values('Harish Joshi'); Query OK, 1 row affected (0.05 sec) mysql> insert into employee values('Harish Joshi'); ERROR 1062 (23000): Duplicate entry 'Harish Joshi' for key 1 mysql> insert into employee values('Rinku roy'); Query OK, 1 row affected (0.03 sec) mysql> insert into employee values('Vinod Kumar'); Query OK, 1 row affected (0.04 sec) mysql> select *from employee; +---------------+ | employee_name | +---------------+ | Deepak Kumar | | Harish Joshi | | Rinku roy | | Vinod Kumar | +---------------+ 4 rows in set (0.04 sec)

Here is the code of java program that retrieves all the employee data from database and displays on the console:
/* Import JDBC core packages. Following statement imports the java.sql package, which contains the JDBC core API. */ import java.sql.*; public class RetriveAllEmployees{ public static void main(String[] args) { System.out.println("Getting All Rows from employee table!"); Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String db = "jdbc"; String driver = "com.mysql.jdbc.Driver"; String user = "root"; String pass = "root"; try{ Class.forName(driver); con = DriverManager.getConnection(url+db, user, pass); Statement st = con.createStatement(); ResultSet res = st.executeQuery("SELECT * FROM employee"); System.out.println("Employee Name: " ); while (res.next()) { String employeeName = res.getString("employee_name"); System.out.println(employeeName ); } con.close(); } catch (ClassNotFoundException e){ System.err.println("Could not load JDBC driver"); System.out.println("Exception: " + e); e.printStackTrace(); } catch(SQLException ex){ System.err.println("SQLException information"); while(ex!=null) { System.err.println ("Error msg: " + ex.getMessage()); System.err.println ("SQLSTATE: " + ex.getSQLState()); System.err.println ("Error code: " + ex.getErrorCode()); ex.printStackTrace(); ex = ex.getNextException(); // For drivers that support chained excep tions } } } }

Explanation of JDBC Steps:


y

Loading Driver Loading Database driver is very first step towards making JDBC connectivity with

the database. It is necessary to load the JDBC drivers before attempting to connect to the database. The JDBC drivers automatically register themselves with the JDBC system when loaded. Here is the code for loading the JDBC driver: Class.forName(driver).newInstance();
y

Establishing Connection In the above step we have loaded the database driver to be used. Now its time to make the connection with the database server. In the Establishing Connection step we will logon to the database with user name and password. Following code we have used to make the connection with the database: con = DriverManager.getConnection(url+db, user, pass); Executing Statements In the previous step we established the connection with the database, now its time to execute query against database. You can run any type of query against database to perform database operations. In this example we will select all the rows from employee table. Here is the code that actually execute the statements against database: ResultSet res = st.executeQuery( "SELECT * FROM employee" ); Getting Results In this step we receives the result of execute statement. In this case we will fetch the employees records from the recordset object and show on the console. Here is the code: while (res.next()) { String employeeName = res.getInt( " employee_name " ); System.out.println( employeeName ); } Closing Database Connection Finally it is necessary to disconnect from the database and release resources being used. If you dont close the connection then in the production environment your application will fail due to hanging database connections. Here is the code for disconnecting the application from database: con.close();

In this section you learnt about the JDBC Steps necessary for performing database operations. Output of program: C:\vinod>javac RetriveAllEmployees.java C:\vinod>java RetriveAllEmployees Getting All Rows from employee table!

Employee Name: Deepak Kumar Harish Joshi Rinku roy Vinod Kumar
Java Database Connectivity or in short JDBC is a technology that enables the java program to manipulate data stored into the database.

JDBC - Java Database Connectivity Tutorials


Introduction to JDBC
Java started as an elegant and promising Web programming language. Thereafter, its transition to hard-core computing environment is a phenomenal feat. Apart from its significance on clientside programming, Java has been outstanding in developing mission-critical enterprise-scale applications and hence its immense contribution to server-side computing gets all round attention. Thus Java as a programming language for enterprise computing has been doing well for the past couple of years. As every enterprise includes a database, Sun Microsystems has to come with necessary features for making Java to shine in database programming as well. In this overview, we discuss about the role of Java Database Connectivity in accomplishing database programming with ease.

Database Programming with Java


Java provides database programmers some distinct advantages, such as easy object to relational mapping, database independence and distributed computing. For languages, such as C++ and Smalltalk, there is a need for tools for mapping their objects to relational entities. Java provides an alternative to these tools that frees us from the proprietary interfaces associated with database programming. With the "write once, compile once, run anywhere" power that JDBC offers us, Java's database connectivity allows us to concentrate on the translation of relational data into objects instead of how we can get that data from the database. A Java database application does not care what its database engine is. No matter how many times the database engine changes, the application itself need never change. In addition, a company can build a class library that maps its business objects to database entities in such a way that applications do not even know whether or not their objects are being stored in a database. Java affects the way we distribute and maintain application. Currently a Web application allows user to download a bunch of flight information as an HTML page. While viewing the page for a particular flight, suppose some one makes a reservation for a seat on that flight and this process will not be available to the viewers as the page is just a copy of data from the database. To view the change that just occurred, the viewers again have to contact the database to get the latest data. If we reconstruct the same Web application using Java RMI to retrieve the data from a single flight object on the server, any number of users can view the data simultaneously and if there is

any reservation or any change taking place, immediately the changes made to the data will be sent back to all the users and hence the users can avail the latest data at any time. Thus JDBC can combine with Java RMI to develop distributed enterprise-scale mission-critical three-tier database applications.

JDBC for Relational Databases


There are three main database technologies. They are relational, object and object-relational. A Java application can access any one of these database architectures. The overwhelming majority of today's database applications use relational databases. The JDBC API is thus heavily biased toward relational databases and their standard query language, SQL. Relational databases find and provide relationships between data and Java, as a object solution makes common cause with relational database technology due to the fact that object-oriented philosophy dictates that an object's behavior is inseparable from its data. In choosing the object-oriented reality of Java, we need to create a translation layer that maps the relational world into our object world. Thus with the goal of accessing relational databases, JDBC API specification has been defined by Sun Microsystems with the help of popular database vendors.

What is JDBC?
JDBC is essentially an Application Programming Interface (API) for executing SQL statements, and extracting the results. Using this API, we can write database clients, such as Java applets, servlets and Enterprise JavaBeans, that connect to a relational database, such as Oracle, MySQL, Sybase, Informix, Ingres, PostgreSQL, or any other database that implements this API, execute SQL statements, and process the results extracted from the database.

JDBC Versions
JDBC 2.0 API is the latest version of JDBC API available in the java.sql package. The previous version focused primarily on basic database programming services such as creating connections, executing statements and prepared statements, running batch queries, etc. However, the current API supports batch updates, scrollable resultsets, transaction isolation, and the new SQL:1999 data types such as BLOB and CLOB in addition to the SQL2 data types. JDBC 2.0 Optional Package API is available in the javax.sql package and is distributed with the enterprise edition of Java 2, that is J2EE. The optional package addresses Java Naming and Directory Interface (JNDI)-based data sources for managing connections, connection pooling, distributed transactions, and rowsets.

The Benefits of JDBC


The JDBC API provides a set of implementation-independent generic database access methods for the above mentioned SQL-compliant databases. JDBC abstracts much of the vendor-specific details and generalizes the most common database access functions. Thus resulted a set of classes and interfaces of the java.sql package that can be used with any database providing JDBC connectivity through a vendor-specific JDBC driver in a consistent way. Thus if our application

conforms to the most commonly available database features, we should be able to reuse an application with another database simply by switching to a new JDBC driver. In other words, JDBC enables us to write applications that access relational databases without any thought as to which particular database we are using. Also database connectivity is not just connecting to databases and executing statements. In an enterprise-level application environment, there are some important requirements to be met, such as optimizing network resources by employing connection pooling, and implementing distributed transactions. JDBC has all these features in accomplishing advanced database programming.

The JDBC Drivers


A database vendor typically provides a set of APIs for accessing the data managed by the database server. Popular database vendors have supplied some proprietary APIs for client access. Client applications written in native languages such as C and C++ can make these API calls for database access directly. The JDBC API provides a Java-language alternative to these vendorspecific APIs. Though this takes away the need to access vendor-specific native APIs for database access, the implementation of the JDBC layer still need to make these native calls for data access. JDBC accomplishes its goals through a set of Java interfaces, each gets implemented differently by different vendors. The set of classes that implement the JDBC interfaces for a particular database engine is called a JDBC driver. Hence the necessity of a JDBC driver for each database server. In building a database application, we do not have to think about the implementation of these underlying classes at all as the whole point of using JDBC is to hide the specifics of each database and let us concentrate on our application. A JDBC driver is a middleware layer that translates the JDBC calls to the vendor-specific APIs. The Java VM uses the JDBC driver to translate the generalized JDBC calls into vendor-specific database calls that the database understands. There are a number of approaches for connecting from our application to a database server via a database driver. JDBC-ODBC Bridge - Open Database Connectivity (ODBC) was developed to create a single standard for database access in the Windows environment. ODBC is a Windows API standard for SQL and it is based on X/Open Call-Level Interface (CLI) specification, which is a standard API for database access. CLI is intended to be vendor, platform, and database neutral. But ODBC API defines a set of functions for directly accessing the data without the need for embedding SQL statements in client applications coded in higher level languages. The JDBC API is originally based on the ODBC API. Thus, it becomes feasible for the first category of JDBC drivers providing a bridge between the JDBC API and the ODBC API. This bridge translates the standard JDBC calls to corresponding ODBC calls. The driver then delegates these calls to the data source. Here, the Java classes for the JDBC API and the JDBCODBC bridge are invoked within the client application process. Similarly, the ODBC layer executes in another process. This configuration requires the client application to have the JDBC-

ODBC bridge API, the ODBC driver, and the native language level API, such as the OCI library for Oracle installed on each client machine. Each data access call has to go through many layers, this approach for data access is inefficient for high-performance database access requirements. Though this is not a preferred one, this has to be used in some situations for example, a Microsoft Access 2000 database can be only be accessed using the JDBC-ODBC bridge. Part Java, Part Native Driver - This approach use a mixture of Java implementation and vendorspecific native APIs for data access. This one is a little bit faster than the earlier one. When a database call is made using JDBC, the driver translates the request into vendor-specific API calls. The database will process the request and send the results back through the API, which will forward them back to the JDBC driver. The JDBC driver will format the results to confirm to the JDBC standard and return them to the program. In this approach, the native JDBC driver, which is part Java and part native code, should be installed on each client along with the vendorspecific native language API. The native code uses vendor-specific protocols for communicating with the database. The improved efficiency makes this a preferred method over the use of the earlier one. Intermediate Database Access Server This approach is based on intermediate (middleware) database servers with the ability to connect multiple Java clients to multiple database servers. In this configuration, clients connect to various database servers via an intermediate server that acts as a gateway for multiple database servers. While the specific protocol used between clients and the intermediate server depends on the middleware server vendor, the intermediate server can use different native protocols to connect to different databases. The Java client application sends a JDBC call through a JDBC driver to the intermediate data access server. The middle-tier then handles the request using another driver, for example the above one, to complete the request. This is good because the intermediate server can abstract details of connections to database servers. Pure Java Drivers - This a pure Java alternative to part Java, part native driver. These drivers convert the JDBC API calls to direct network calls using vendor-specific networking by making direct socket connections with the database like Oracle Thin JDBC Driver. This is the most efficient method of accessing databases both in performance and development time. It also the simplest to deploy since there are no additional libraries or middleware to install. All major database vendors, such as Oracle, Sybase, and Microsoft, provide this type of drivers for their databases.

Alternatives to JDBC
There are two major alternatives to JDBC at present. They are ODBC and SQLJ, a non-approved Java standard for database access. Without JDBC, only disparate, proprietary database access solutions exist. These solutions force the developer to build a layer of abstraction on top of them in order to create databaseindependent code. The ODBC solution provide this universal abstraction layer for languages,

such as C and C++, and popular developmental tools, such as Delphi, PowerBuilder, and VisualBasic. But ODBC can not enjoy the platform independence of Java as ODBC is restricted to Windows platform. On using JDBC, the server application can pick the database at run time based on which client is connecting. Thus JDBC facilitates to change the database just by changing the JDBC URL and driver name without adding any new code. Many of the major database vendors have designed SQLJ through joint work. SQLJ is a specification for writing embedded SQL in Java applications that a preprocessor can read and turn into JDBC calls.
First Step towards JDBC! First Step towards JDBC Introduction T his article introduce you with JDBC and shows you how to create a database application to access the databases. For the shake of simplicity, in very first example Access database and

First Step towards JDBC


Introduction This article introduce you with JDBC and shows you how to create a database application to access the databases. For the shake of simplicity, in very first example Access database and Sun's JDBC-ODBC drivers are used. In the later sections we will show you how to use JDBC from your servlets or JSP pages to create dynamic pages or to store the data received from visitors. What is JDBC? Java Database Connectivity or JDBC for short is set of Java API's that enables the developers to create platform and database independent applications in java. The biggest advantage of programming in Java is its platform independence. An application written to access the MS Access database on Win 95/Win NT platform can work on Linux against Oracle database, only by changing the name of driver, provided none of the database calls it makes are vendor specific. What are JDBC Drivers? JDBC Drivers are set of classes that enables the Java application to communicate with databases. Java.sql that ships with JDK contains various classes for using relational databases. But these classes do not provide any implementation, only the behaviours are defined. The actual implementaions are done in third-party drivers. Third party vendors implements the java.sql.Driver interface in their database driver. JDBC Drivers Types Sun has defined four JDBC driver types. These are:
1. Type 1: JDBC-ODBC Bridge Driver The first type of JDBC dirver is JDBC-ODBC Bridge which provide JDBC access to any ODBC complaint databases through ODBC drivers. Sun's JDBC-ODBC bridge is example of type 1 driver.

2. Type 2: Native -API Partly - Java Driver Type 2 drivers are developed using native code libraries, which were originally designed for accessing the database through C/C++. Here a thin code of Java wrap around the native code and converts JDBC commands to DBMS-specific native calls. 3. Type 3: JDBC-Net Pure Java Driver Type 3 drivers are a three-tier solutions. This type of driver communicates to a middleware component which in turn connects to database and provide database connectivity. 4. Type 4: Native-Protocol Pure Java Driver Type 4 drivers are entirely written in Java that communicate directly with vendor's database through socket connection. Here no translation or middleware layer, are required which improves performance tremendously.

Links to JDBC Drivers Site

Here is the link of some of the site providing the JDBC drivers:

1. MERANT DataDirect provides JDBC driver technology through n-tier, server-based data connectivity and high-performance, DBMS-independent JDBC middleware. 2. MM MySQL JDBC DRIVERS - 100% pure java driver for MySQL and is distributed under the GNU LGPL. 3. The mSQL JDBC Driver-A pure-java JDBC driver for mSQL was created and is being maintained by George Reese from The Center for Imaginary Environments.

A list of currently available JDBC drivers can be found at http://java.sun.com/products/jdbc/jdbc.drivers.html You can easily find the JDBC driver for SQL Server and all other database servers by surfing the following link: http://industry.java.sun.com/products/jdbc/drivers
Accessing Database from servlets through JDBC! Accessing Access Database From Servlet T his article shows you how to access database from servlets. Here I am assuming that you are using win95/98/2000 and running Java Web Server. For the sake of

Accessing Access Database From Servlet


This article shows you how to access database from servlets. Here I am assuming that you are using win95/98/2000 and running Java Web Server. For the sake of simplicity I have used Microsoft Access Database as backend and Sun's JDBC-ODBC bridge to connect to access data source. First of all download the source code and database used in this tutorial and now follow the following the steps.
1. Unzip the downloaded file into your favorite directory.

2. Create an ODBC data source "emaildb" by selecting "emaildb.mdb" database from unzipped folder. 3. Compile you emaildb.java file, move emaildb.class file to Java Web Servers servlets directory and register the servlet. Now open your browser and run the servlet.

Your browser should display the data from database.

Now we will examine how the code works.


import import import import import import java.io.*; java.util.Enumeration; javax.servlet.*; javax.servlet.http.*; java.sql.*; java.net.*;

public class emaildb extends HttpServlet{ Connection theConnection; private ServletConfig config; public void init(ServletConfig config) throws ServletException{ this.config=config; } public void service (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { HttpSession session = req.getSession(true); res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<HTML><HEAD><TITLE>Emai List.</TITLE>"); out.println("</HEAD>"); out.println("<BODY bgColor=blanchedalmond

text=#008000 topMargin=0>"); out.println("<P align=center><FONT face=Helvetica><FONT color=fuchsia style=\"BACKGROUND-COLOR: white\"><BIG><BIG>List of E-mail addresses.</BIG></BIG></FONT></P>"); out.println("<P align=center>"); out.println("<TABLE align=center border=1 cellPadding=1 cellSpacing=1 width=\"75%\">");

out.println("<TR>"); out.println("<TD>Name</TD>"); out.println("<TD>E-mail</TD>"); out.println("<TD>Website</TD></TR>"); try{

//Loading Sun's JDBC ODBC Driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

//Connect to emaildb Data source theConnection = DriverManager.getConnection("jdbc:odbc:emaildb", "admin", "");

Statement theStatement=theConnection.createStatement(); ResultSet theResult=theStatement.executeQuery("select * from emaillists"); //Select all records from emaillists table. //Fetch all the records and print in table while(theResult.next()){ out.println(); out.println("<TR>"); out.println("<TD>" + theResult.getString(1) +

"</TD>"); out.println("<TD>" + theResult.getString(2) + "</TD>"); String s=theResult.getString(3); out.println("<TD><a href=" + s + ">" + s + "</a></TD>"); out.println("</TR>"); } theResult.close();//Close the result set theStatement.close();//Close statement theConnection.close(); //Close database Connection }catch(Exception e){ out.println(e.getMessage());//Print trapped error. } out.println("</TABLE></P>");

out.println("<P>&nbsp;</P></FONT></BODY></HTML>"); } public void destroy(){ } }

Here we have used Sun's JDBC-ODBC Bridge, but we can easily replace the driver in order to connect the servlet to another database. For example, we can use the following code to connect our program to MySQL database.
Class.forName("org.gjt.mm.mysql.Driver"); theConnection = DriverManager.getConnection("jdbc:mysql://192.192.10.1:3306/mysql",

"mysql","mysql");

JDBC driver for MySQL is available at www.mysql.com and is free. Here I have assumed that your mysql server is running at port 3306 of computer, whose IP address is 192.192.10.1.
JDBC stands for Java Database Connectivity. For connectivity with the database we uses JDBC.

JDBC Components
JDBC stands for Java Database Connectivity. For connectivity with the database we uses JDBC. It establish connection to access the database. This provides a set of classes in the java.sql package for Java applications to communicate with databases. Mostly databases used a language called SQL. SQL stands for Structured Query Language. JDBC gives you the opportunity to communicate with standard database. JDBC includes four components: 1. The JDBC API The JDBC API gives access of programming data from the Java. To use this, applications can execute SQL statements and retrieve results and updation to the database. The JDBC API is part of the Java platform, it includes the Java Standard Edition. 2. JDBC Driver Manager The JDBC DriverManager is the class in JDBC API. The objects of this class can connect Java applications to a JDBC driver. DriverManager is the very important part of the JDBC architecture. 3. JDBC Test Suite The JDBC driver test suite helps JDBC drivers to run your program. They are not exhaustive,they do exercise with important features in the JDBC API. 4. JDBC-ODBC Bridge The Java Software bridge provides JDBC access via ODBC drivers.You have to load ODBC binary code for client machines for using this driver. This driver is very important for application server code has to be in Java in a three-tier architecture. The program below describes how to run the JDBC program with MySql. JDBCExample.java is the program to understand how to establish the connection with database. The Url, Connection, Driver, Statement, Resultset etc. and how to process the java code with database is mentioned here. JDBCExample.java

import java.sql.*; public class JDBCExample { public static void main(String a[]) { Connection conn = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "vineej"; String driver = "com.mysql.jdbc.Driver"; String userName = "vineej"; String password = "no"; try { Class.forName(driver).newInstance(); Connection con =DriverManager.getConnection(url+dbName,userName,password); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("SELECT *

from Employee");
System.out.println("Results"); while( rs.next() ) { String data = rs.getString(1); System.out.println( data ); } st.close(); } catch( Exception e ) { System.out.println(e.getMessage()); e.printStackTrace(); } } }

Description of program This program making the connection between MySQL database and java with the help of many types of APIs interfaces.First connected it and then execute a query.It shows the result, like in above example it displays the all employees in the existing table Employee. Description of code 1. Connection An interface in java.sql package that provides connection with the database like- MySQL and java files. The SQL statements are executed within the context of the Connection interface. 2. Class.forName(String driver) forName() is static method of the "Class" class . This loads the driver class and returns Class instance. It takes string type value as an argument and matches the class with string. 3. DriverManager This class of java.sql package controls the JDBC drivers. Each driver has to be registered with this class.

4. getConnection(String url, String userName, String password) This static method of DriverManager class makes a connection with database url. It takes these given arguments of string type. url - Database url where stored or created your database userName - User name of MySQL password -Password of MySQL 5. con.close() This method of Connection interface is used for closing the connection. All the resources will be free occupied by the database. 6. printStackTrace() The method is used to show error messages. If the connection is not connected then it throws the exception and print the message. Java Database Connectivity StepsSome steps are given below of the JDBC 1. First import the java.sql package import java.sql.*; The star '*' indicates that all of the classes in the java.sql and java.io packages are to be imported. 2. Loading a database driver In this step, the driver class loaded by calling Class.forName() with the Driver class. Class is a class in java.lang package. Class.forName("com.mysql.jdbc.Driver"); 3. Creating a jdbc Connection The objects defined by DriverManager class to establish the applications with the JDBC driver. This class manages the JDBC drivers which is installed on the system. getConnection() is the method by which it can connect. It uses the username, password, and a jdbc url to make the connection with database. try{ Connection con=DriverManager.getConnection(url,"userName","password"); } catch( SQLException x ){ System.out.println( "e.printStackTrace" ); } 4. Creating a jdbc Statement object When an connection is established then we can interact with the database. Connection interface

defines methods for interacting with the database. It used to instantiate a Statement by using the createStatement() method. Statement st = con.createStatement(); 5. Executing a statement with the Statement object This interface defines methods which is used to communicate with database. This class has three methods to execute the statements- executeQuery(), executeUpdate(), and execute(). For SELECT statements, executeQuery() method will be used. For create or modify tables, the executeUpdate() method is used. executeQuery() method returns the result of the query in the form of ResultSet object and executeUpdate() method returns the number of rows affected from execution of the query. ResultSet rs = st.executeQuery("SELECT * from Employee"); 6. Getting ResultSet object Executing the executeQuery() method returns the result in the form of ResultSet object. We can now operate on this object to extract the rows values returned from the execution of the query. Its next() method sets the pointer to the first row and getX() methods can be used to get different types of data from the result set. while( rs.next() ) { String data = rs.getString(1); System.out.println( data ); }
This example counts the number of columns in a table. The ResultSetMetaData interface can be used to get type and properties information of columns in a ResultSet.

Get Column Count using ResultSet in SQL


This example counts the number of columns in a table. The ResultSetMetaData interface can be used to get type and properties information of columns in a ResultSet. The ResultSetMetaData object can be obtained by invoking getMetaData() method on ResultSet object. In this program you will see how JDBC connection is established and how to get required data, like the number of columns.

GetColumnCount.java
import java.sql.*; public class GetColumnCount { public static void main(String[] args) throws Exception { String driver = "com.mysql.jdbc.Driver"; String url = "jdbc:mysql://localhost:3306/";

String username = "vineej"; String password = "vineej"; String dbName= "no"; Class.forName(driver); Connection conn = DriverManager.getConnection(url+dbName, username, passw ord); System.out.println("Connected"); Statement st = conn.createStatement(); ResultSet rs = st.executeQuery("SELECT * FROM Student"); ResultSetMetaData rsmd = rs.getMetaData(); int NumOfCol=rsmd.getColumnCount(); System.out.println("Number of Columns="+NumOfCol); st.close(); conn.close(); } }

Java Database Connectivity Steps 1.Connection An interface in java.sql package that provides connection with the database like- MySQL and java files. The SQL statements are executed within the context of the Connection interface. 2.Class.forName(String driver) Class.forName method is static. This driver load the class and returns class instance and takes string type value and after that it will match the class with string. 3.DriverManager It is a class of java.sql package that controls the JDBC drivers. Each driver has to be register with this class. 4.getConnection(String url, String userName, String password) This method establishes a connection to specified database url. It takes three string types of arguments like: url: - Database url where stored or created your database userName: - User name of MySQL password: -Password of MySQL 5.con.close() This method is used for disconnecting the connection. It frees all the resources occupied by the database. 6.printStackTrace() The method is used to show error messages. If the connection is not established then exception is thrown and print the message. Description of code 1. First import the java packages

import java.sql.*; The star '*' indicates that all of the classes in the java.sql and java.io packages are to be imported. 2. Loading a database driver In this step, the driver class loaded by calling Class.forName() with the Driver class. Class is a class in java.lang package. Class.forName("com.mysql.jdbc.Driver"); 3. Creating a jdbc Connection The objects defined by DriverManager class to establish the applications with the JDBC driver. This class manages the JDBC drivers which is installed on the system. getConnection() is the method by which it can connect. It uses the username, password, and a jdbc url to make the connection with database. Connection conn = DriverManager.getConnection(url+dbName, username, password); 4. Creating a jdbc Statement object When an connection is established then it can interact with the database. Connection interface defines methods for managing the database. It used to instantiate a Statement by using the createStatement() method. Statement st = conn.createStatement(); 5. Executing a statement with the Statement object, and returning a jdbc resultSet This interface defines methods which is used to communicate with database. This class has three methods to execute the statements- executeQuery(), executeUpdate(), and execute(). To SELECT statement, executeQuery() method will be used. For create or modify tables, the method to use is executeUpdate. ResultSet rs = st.executeQuery("SELECT * FROM Student"); 6. Getting ResultSetMetaData object ResultSet has method getMetaData() which returns the ResultSet MetaData object which provides meta information of the result set. ResultSetMetaData rsmd = rs.getMetaData(); 7. Getting no of columns getColumnCount() method on ResultSetMetaData object returns the number of columns for the result set returned from the query. int NumOfCol=rsmd.getColumnCount();
SQL commands are divided into categories like DML (Data Manipulation language), DDL (Data definition language), TCL (Tranction control language) and DCL (Data control language).

Common SQL Commands

SQL commands are divided into categories like DML (Data Manipulation language), DDL (Data definition language), TCL (Tranction control language) and DCL (Data control language). Here are a list of SQL commands. 1. DML COMMANDS INSERT UPDATE SELECT DELETE 2.DDL COMMANDS CREATE ALTER DROP 3.TCL COMMANDS COMMIT ROLLBACK 4.DCL COMMANDS GRANT REVOKE The table given below (named Student) has two fields id and Name. Student Table id Name 1 Ravi 2 Ajay The commands are based on this table: 1. DML COMMANDS INSERT ROWS The syntax for this command is insert into tablename(colname1,colname2) values(value1,value2); Example: insert into Student (id, Name) values(1,'Ravi'); This statement is used to insert a row of data into Student table.

UPDATE ROWS The syntax for this command is update tablename set colname1=colvalue where colname2=colvalue; Example: update Student set Name = 'Ajay' where id = 2; This command has updated the Name 'Rose' in Student table whose id is 2. SELECT ROWS This command is used to select rows from a table.The syntax for this command is select colname1,colname2 from tablename; Example: select Name from Student; It will display all names from Student table. Like Ravi. DELETE ROWS The syntax for this command isdelete from tablename where [search_conditions]; Example: delete from Student where id=1; This statement is used to delete the row from Student table where the student id is 1. 2. DDL COMMANDS CREATE TABLE This statement is used to create a table. The syntax for this command is create table tablename (colname1 datatype [constraint], colname2 datatype [constraint]); Example: create table Student (id number(4) primary key, Name varchar2(20)); It creates the table Student which has two fields id i.e. Student id and Name i.e. the student name. The number and varchar2 are the data types of id and Name respectively. Field 'id' has the

size 4 means it can take id up to 4 digits and same for Name, it can take the size up to 20 characters. And also added the constraint Primary key to the field 'id'. ALTER TABLE This command is used to add, drop columns in a table. The syntax for this command is alter table tablename add colname1 datatype [constraint]; alter table tablename drop column colname1; Example: alter table Student add DOB date; This command is used to add new field DOB in Student table. It's datatype is date. This is also used for drop column from the table. It will drop the DOB field by query given belowAlter table Student drop column DOB; DROP TABLE The syntax for this command isdrop table tablename; Example: drop table Student; This statement is used for destroy the table from database. 3.TCL COMMANDS COMMIT This command is used for save the work done. The syntax is: COMMIT; ROLLBACK This command is used to restore the database to original since the last commit. The syntax isROLLBACK; 4. DCL COMMANDS GRANT This command is used for gives access privileges to users for database. The syntax isGRANT dba to username;

REVOKE This command is used for withdraws access privileges to users for database. The syntax isREVOKE permissions on tablename from username;
Whenever we need to select data from two or more tables, we have to perform a join operation.

Using JOINING Operation in JDBC


Whenever we need to select data from two or more tables, we have to perform a join operation. Tables in a database can be related to each other with keys. A primary key is a column with a unique value for each row. Each primary key value must be unique within the table. We will use two related tables Student and testing, to use JOIN. The SQL JOIN clause is used to retrieve data from two or more tables joined by same fields. The most common thing is a primary key from one table matches a foreign key in another table. Consider the SQL JOIN statement below: SELECT * FROM Student s,testing t where s.Name=t.name; TYPE OF JOINS There are two types of SQL JOINS INNER and OUTER Joins. By default it takes INNER JOIN. The INNER JOIN will select all rows from both tables as match between the columns. In case we have a students in the Student table, this student will not be listed in the result of our SQL query above. SQL INNER JOIN The join clause binds columns of both the tables to create a single table. Join matches the columns in both tables. There are two types of join statements, inner and outer joins. An inner join returns all rows that result in a match such as the example above. SQL OUTER JOIN This join clause has two parts. 1.SQL LEFT OUTER JOIN A Left outer join returns all rows of the left of the conditional even if there is no right column to match. 2.SQL RIGHT OUTER JOIN A right outer join will display rows on the right side of the conditional that may or may not have a match. This program is about to join the two tables Student and testing which has the Name and name columns respectively. Which data will match with the tables it will retrieve. Like the Name of Student table and name of testing will match the data and retrieve the all matched data.

JoinPro.java
import java.sql.*; public class JoinPro { public static void main(String a[]) { Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "vineej"; String driver = "com.mysql.jdbc.Driver"; String userName = "vineej"; String password = "no"; try { Class.forName(driver).newInstance(); con = DriverManager.getConnection(url+dbName,userName,password) ; Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select * from Student s,testing t where s.Name=t.name"); while( rs.next() ) { String data = rs.getString(1); System.out.println( data ); } System.out.println("Results"); st.close(); } catch( Exception e ) { System.out.println(e.getMessage()); e.printStackTrace(); } } }

Describe the program In this program we used how we retreive the data from two or more tables with the JDBC. Student and testing is the name of tables and Name and name are the columns of tables.In the above program see s.Name and t.name, here s and t are the two aliases of tables we have created. They represents the tables at the time of joining. Coding steps of the program 1.First in the program we import the java.sql and java.io packages then define the SelectState class. import java.sql.*; 2.Create a connection with the MySql database. con = DriverManager.getConnection(url+dbName,userName,password); 3.Create statement and then execute query with the SELECT statement. Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select * from Student s,testing t where s.Name=t.name");

4.Finally got the result by the getString() method. while( rs.next() ) { String data = rs.getString(1); System.out.println( data ); } 5.After all connection should be closed. con.close(); 6.printStackTrace() method. The method is used to show error messages. If the connection is not connected then it throws the exception and print the message.
Where clause is used to retrieve the data from a table based on some specific conditions.

Using WHERE Clause in JDBC


Where clause is used to retrieve the data from a table based on some specific conditions. It allows to filter the data from a table, a WHERE clause can be added to the SELECT statement. The WHERE clause searches the specific results by the SELECT statement. Example of WHERE Clause SELECT Name from Employee where Employee_ID=1; Where clause Using LIKE 1.The following SQL statement will return employees with names that start with 'a': SELECT * FROM Employee WHERE Name LIKE 'a%'; 2.The following SQL statement will return employees with names that end with 'y': SELECT * FROM Employee WHERE Name LIKE '%y'; 3.The following SQL statement will return employees with names that contain the pattern 'as': SELECT * FROM Employee WHERE Name LIKE '%as%'; A "%" and _ sign is known as wildcards, both before and after the pattern.

Operators Used With WHERE Clause = Equal <> Not Equal

> Greater than < Less than >= Greater than or Equal <= Less than or Equal BETWEEN Between an inclusive range LIKE Search for pattern This program is concern with, how to get selected data from a table. Like- If any specific data desired then it would be easier as compare to search in whole table. So according to the Query the data would retrieve. In this program we used employee table which has Employee_ID field. So it will search in table and then give the result of an employee whose Employee_ID is 1. WhereClause.java
import java.sql.*; public class WhereClause { public static void main(String a[]) { Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "vineej"; String driver = "com.mysql.jdbc.Driver"; String userName = "vineej"; String password = "no"; try { Class.forName(driver).newInstance(); con = DriverManager.getConnection(url+dbName,userName,password); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select Name from Employee where Employee_ID=1 "); System.out.println("Results"); while( rs.next() ) { String data = rs.getString(1); System.out.println( data ); } st.close(); } catch( Exception e ) { System.out.println(e.getMessage()); e.printStackTrace(); } } }

Description of program This program making the connection between MySQL database and java with the help of many types of APIs interfaces. When it will be execute then it shows "Results" .The Employee is the table name and Employee_ID is the column name. Description of code 1.Connection An interface in java.sql package that provides connection with the database like- MySQL and java files. The SQL statements are executed within the context of the Connection interface. 2.Class.forName(String driver) Class.forName method is static. This driver load the class and returns class instance and takes string type value and after that it will match the class with string. 3.DriverManager It is a class of java.sql package that controls the JDBC drivers. Each driver has to be register with this class. 4.getConnection(String url, String userName, String password) This method establishes a connection to specified database url. It takes three string types of arguments like: url - Database url where stored or created your database userName - User name of MySQL password -Password of MySQL 5.con.close() This method is used for disconnecting the connection. It frees all the resources occupied by the database. 6.printStackTrace() The method is used to show error messages. If the connection is not connected then it throws the exception and print the message.
The SELECT statement is used to select data from a table. For terminating a statement, semicolon is used.

Using Select Statements in JDBC


The SELECT statement is used to select data from a table. For terminating a statement, semicolon is used. When we want to fetch the data from any table then we have to use SELECT statement. The Query can be written as below: SELECT * FROM employee;

This Example SelectState.java is concern with Select Statements. You have to just create the connection with database and execute the Select Statement.

SelectState.java
import java.sql.*; public class SelectState { public static void main(String a[]) { Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "vineej"; String driver = "com.mysql.jdbc.Driver"; String userName = "vineej"; String password = "no"; try { Class.forName(driver).newInstance(); con = DriverManager.getConnection(url+dbName,userName,password); Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select Name from

Employee");
System.out.println("Results"); while( rs.next() ) { String data = rs.getString(1); System.out.println( data ); } st.close(); } catch( Exception e ) { System.out.println(e.getMessage()); e.printStackTrace(); } } }

Description of the program In this program, we will learn how to retrieve the data from any table with the JDBC. Employee is the name of a table and Name is one of the column of table. By the SELECT Statement we can retrieve the data. Description of Code 1.First in the program we import the java.sql package then define the SelectState class. import java.sql.*;

2.Create a connection with MySql database. con = DriverManager.getConnection(url+dbName,userName,password); 3.Create statement and then execute query with the SELECT statement. Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select Name from Employee"); 4.Finally got the result by the getString() method. while( rs.next() ) { String data = rs.getString(1); System.out.println( data ); } 5. At the end, connection should be disconnected. con.close(); 6. printStackTrace() method The method is used to show error messages. If there is any problem while execution then it throws the exception and prints the message.
This is detailed java program to connect java application with mysql database and execute query to display data from the specified table.

Display Data from Database in JSP


This is detailed java program to connect java application with mysql database and execute query to display data from the specified table. Before running this java code you need to copy a mysql connector jar file (mysql-connectorjava-3.1.6-bin.jar) in the jdk1.6.0_01\lib and set class path for this jar file. This is first jsp page that has a link 'show data from table', user can show all the data from table after clicking link. This is the code of first welcome jsp page.

welcome_to_database_query.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<%@ page import="java.sql.*" %> <%@ page import="java.io.*" %> <html> <head> <title>display data from the table using jsp</title> </head> <body> <TABLE style="background-color: #ffffcc;"> <TR> <TD align="center"><h2>To display all the data from the table click here...</h2></TD> </TR> <TR> <TD align="center"><A HREF="ConnectJspToMysql.jsp"> <font size="4" color="blue">show data from table</font> </A></TD> </TR> </TABLE> </body> </html>

Create a new directory in Tomcat-6.0.16/webapps/ and Save this code with the name "welcome_to_database_query.jsp" in Tomcat-6.0.16/webapps/user along with WEB-INF directory. Start tomcat server and type url 'http://localhost:8080/user/welcome_to_database_query.jsp' in address bar of browser and run.

This page has a link, to show data from the database click on the link that calls another jsp file named ConnectJspToMysql.jsp

ConnectJspToMysql.jsp page creates connection between application and database. In this code connection is between application and table name 'stu_info' in database 'student'.

ConnectJspToMysql.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ page import="java.sql.*" %> <%@ page import="java.io.*" %> <html> <head> <title>display data from the table using jsp</title> </head> <body> <h2>Data from the table 'stu_info' of database 'student'</h2> <% try { /* Create string of connection url within specified format with machine name, port number and database name. Here machine name id localhost and database name is student. */ String connectionURL = "jdbc:mysql://localhost:3306/student"; // declare a connection by using Connection interface Connection connection = null; /* declare object of Statement interface that is used for executing sql statements. */ Statement statement = null; // declare a resultset that uses as a table for output data from tha table. ResultSet rs = null; // Load JBBC driver "com.mysql.jdbc.Driver" Class.forName("com.mysql.jdbc.Driver").newInstance(); /* Create a connection by using getConnection() method that takes parameters of string type connection url, user name and password to connect to database.*/ connection = DriverManager.getConnection(connectionURL, "root", "root"); /* createStatement() is used for create statement object that is used for sending sql statements to the specified database. */ statement = connection.createStatement(); // sql query to retrieve values from the secified table. String QueryString = "SELECT * from

stu_info"; rs = statement.executeQuery(QueryString); %> <TABLE cellpadding="15" border="1" style="backgroundcolor: #ffffcc;"> <% while (rs.next()) { %> <TR> <TD><%=rs.getInt(1)%></TD> <TD><%=rs.getString(2)%></TD> <TD><%=rs.getString(3)%></TD> <TD><%=rs.getString(4)%></TD> </TR> <% } %> <% // close all the connections. rs.close(); statement.close(); connection.close(); } catch (Exception ex) { %> </font> <font size="+3" color="red"></b> <% out.println("Unable to connect to database."); } %> </TABLE><TABLE> <TR> <TD><FORM ACTION="welcome_to_database_query.jsp" method="get" > <button type="submit"><-back</button></TD> </TR> </TABLE> </font> </body> </html>

Save this code with name ConnectJspToMysql.jsp in the same dirctory of welcome_to_database_query.jsp. Click on the link given in the first jsp page,that calls this jsp page and show all data from the table.

Click on the <--back button to go to first page of the application.


A Clob is a Character Large Object in a Database. Clob can be very large depending on the Database up to 4 GB.

Servlet Example To Display Mysql Clob Data


What is Clob? A Clob is a Character Large Object in a Database. Clob can be very large depending on the Database up to 4 GB. It is a rich data type of JDBC. A large character data file can be stored as CLOB type. JDBC provides java.sql.Clob interface for handling large character/text object. Mysql Clob According to the Mysql, there are four text types TINYTEXT, TEXT, MEDIUMTEXT and LONGTEXT which can be taken as CLOB type and have the maximum lengths and storage requirements. The maximum length of TINYTEXT has 255 character (8 bits), TEXT has 16,535 character (16 bits), MEDIUMTEXT has 16,777,216 character (24 bits) and LONGTEXT has 4,294,967,295 character (32 bits). How to define Clob Datatype in Mysql Table

In the table below, you can see "Body" field as "longtext" type in the table "article". Here, Body field represents Clob data.
CREATE TABLE `article` ( `ID` int(11) NOT NULL, `Subject` varchar(256) NOT NULL, `Body` longtext, PRIMARY KEY (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1

Display Mysql Clob Data We have developed a servlet (DisplayClobExample) that accepts the ID of a file and displays the associated file. DisplayClobExample.java
import import import import import import import import import import import import java.io.IOException; java.sql.Clob; java.sql.Connection; java.sql.DriverManager; java.sql.ResultSet; java.sql.SQLException; java.sql.Statement; javax.servlet.ServletException; javax.servlet.ServletOutputStream; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse;

public class DisplayClobExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException{ Clob clobFile = null; Connection con = null; Statement stmt = null; ResultSet rs = null; Integer id = 1; String query = "select Body from article where id = " + id; ServletOutputStream out = response.getOutputStream(); response.setContentType("text/html"); out.println("<html><head><title>Display Clob Example</title></head>");

try { Class.forName("com.mysql.jdbc.Driver"); con =DriverManager.getConnection ("jdbc:mysql://192.168.10.59:3306/example", "root", "root"); stmt = con.createStatement(); rs = stmt.executeQuery(query); if (rs.next()) { clobFile = rs.getClob(1); } else { out.println("<body><h4><font color='red'>There are no any File on id=" + id + "</font></h4></body></html>"); return; } long length = clobFile.length(); String fileData = clobFile.getSubString(1, (int) length); out.println("<body><h4><font color='green'>Successfully Display The Record: </font></h4></body></html>"); out.println(fileData); } catch (Exception e) { out.println("<body><h4><font color='red'>Unable to display" + e.getMessage()+ "</font></h4></body></html>"); return; } finally { try { rs.close(); stmt.close(); con.close(); } catch (SQLException e) { System.out.println(e); } } } }

Mapping of servlet (DisplayClobExample) in web.xml


<servlet> <servletname>DisplayClobExample</servletname> <servletclass>DisplayClobExample</servletclass> </servlet> <servlet-mapping> <servlet-

name>DisplayClobExample</servletname> <urlpattern>/DisplayClobExample</urlpattern> </servlet-mapping>

Run the servlet (DisplayClobExample) by url: http://localhost:8080/JavaExample/DisplayClobExample . The data of the file will be displayed as below:

and if in case any error in database connection exists and there is no file on given id then the following message will be displayed.

This example shows you how to use JDBC's rich data type BLOB. The BLOB type stores/retreives large binary

objects such as PDF files, video clips, JPEG/GIF pictures, and Microsoft word documents.

Servlet Example To Display Mysql Blob Data


This example shows you how to use JDBC's rich data type BLOB. The BLOB type stores/retreives large binary objects such as PDF files, video clips, JPEG/GIF pictures, and Microsoft word documents. A BLOB is a Binary Large Object in a database (represented as column object in a database record/rows). BLOB data can be large up to 2GB or more, depending on the database. getBlob() and setBlob() methods from interfaces like ResultSet, CallableStatemene and PreparedStatement can be used to access an SQL BLOB value. The Blob interface (java.sql.Blob) provides methods like length() to find the length of the value, position() to get the position of a pattern of bytes, getBytes() to retrieves all or part of the BLOB value as an array of bytes etc. According to the JDK 1.4.2, java.sql.Blob interface methods are as follows:
Return Type Method InputStream getBinaryStream() Description Retrieves the blob value designated by this blob value as a stream Retrieve all or part of the blob value that this blob represents as an array of bytes. Returns the no of bytes in the Blob value designated by this Blob object

byte[]

getBytes(long pos, int length)

long

length()

OutputStream setBinaryStream(long Retrieves a stream that can be pos) used to write to the Blob value int setBytes(long pos, byte[] bytes) Write the given array of bytes to the Blob value that this Blob object represent, starting at position pos, and returns the no of bytes written Truncates the blob value that this blob object represents to be len bytes in len

void

truncate(long len)

Mysql BLOBs - Mysql has four kinds of BLOBs:


y y y y

TINYBLOB: The maximum length is 255 characters (8 bits) BLOB: The maximum length is 16,535 characters (16 bits) MEDIUMBLOB: The maximum length is 16,777,216 characters (24 bits) LONGBLOB: The maximum length is 4,294,967,295 characters (32 bits).

Creating The Table In Mysql Database: Table -------pictures Create Table ----------------------------------------CREATE TABLE `pictures` ( `id` int(11) NOT NULL auto_increment, `image` blob, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1

This example shows you how to retrieve the Blob Image from Mysql database using the servlet. DisplayBlobExample.java
import import import import import import import import import import import import import java.sql.Blob; java.sql.ResultSet; java.sql.Statement; java.sql.Connection; java.io.IOException; java.io.InputStream; java.sql.SQLException; java.sql.DriverManager; javax.servlet.ServletException; javax.servlet.ServletOutputStream; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse;

public class DisplayBlobExample extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException { Blob image = null; Connection con = null; Statement stmt = null; ResultSet rs = null; ServletOutputStream out = response.getOutputStream();

try { Class.forName("com.mysql.jdbc.Driver"); con = DriverManager.getConnection("jdbc:mysql://192.168.10.59:3306/ example","root","root"); stmt = con.createStatement(); rs = stmt.executeQuery("select image from pictures where id = '2'"); if (rs.next()) { image = rs.getBlob(1); } else { response.setContentType("text/html"); out.println("<html><head><title>Display Blob Example</title></head>"); out.println("<body><h4><font color='red'>image not found for given id</font> </h4></body></html>"); return; } response.setContentType("image/gif"); InputStream in = image.getBinaryStream(); int length = (int) image.length(); int bufferSize = 1024; byte[] buffer = new byte[bufferSize]; while ((length = in.read(buffer)) != -1) { out.write(buffer, 0, length); } in.close(); out.flush(); } catch (Exception e) { response.setContentType("text/html"); out.println("<html><head><title>Unable To Display image</title></head>"); out.println("<body><h4><font color='red'>Image Display Error=" + e.getMessage() + "</font></h4></body></html>"); return; } finally { try { rs.close(); stmt.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }

Mapping of servlet (DisplayBlobExample) in web.xml


<servlet> <servlet-

name>DisplayBlobExample</servletname> <servletclass>DisplayBlobExample</servletclass> </servlet> <servlet-mapping> <servletname>DisplayBlobExample</servletname> <urlpattern>/DisplayBlobExample</urlpattern> </servlet-mapping> Run the servlet (DisplayBlobExample.java) on this url: http://localhost:8080/JavaExample/DisplayBlobExample. The data of the file will be displayed as below:

and if in case any error in database connection exists and there is no file on given id then the following message will be displayed.

This example shows how to update CLOB data in the database. In our example, servlet InsertClobExample takes url for the CLOB data (the url will be pointing to a text file).

Servlet Example To Update Mysql Clob Data


This example shows how to update CLOB data in the database. In our example, servlet InsertClobExample takes url for the CLOB data (the url will be pointing to a text file). Therefore, we will represent the CLOB as a url.
Mysql Clob

According to the Mysql, there are four text types TINYTEXT, TEXT, MEDIUMTEXT and LONGTEXT which can be taken as CLOB type and have the maximum lengths and storage requirements. The maximum length of TINYTEXT has 255 character (8 bits), TEXT has 16,535 character (16 bits), MEDIUMTEXT has 16,777,216 character (24 bits) and LONGTEXT has 4,294,967,295 character (32 bits).
Table 'article' in Mysql:

The structure of the table 'article' is as follows:


CREATE TABLE `article` ( `ID` int(11) NOT NULL, `Subject` varchar(256) NOT NULL, `Body` longtext, PRIMARY KEY (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1

Creating 'UpdateClobExample' servlet:

The following servlet UpdateClobExample shows how to update data of CLOB type in mysql database through the servlet program. It has two variables:
y y

id (the ID of file). sourceURL (the url of file representing the CLOB; the servlet will open the url, construct a CLOB and update it into the CLOB column of the article table)

Let's update a new record with the following data in the 'article' table:
y y

id (1) sourceURL (http://localhost:8080/JavaExample/images/large.dat)

Source code of UpdateClobExample.java


import import import import import import import import import import import import import import import import import import import import java.io.*; java.util.*; javax.sql.*; javax.servlet.*; javax.servlet.http.*; java.sql.Connection; java.sql.DriverManager; java.sql.ResultSet; java.sql.SQLException; java.net.URL; java.io.IOException; java.io.InputStream; java.net.URLConnection; java.sql.PreparedStatement; java.io.ByteArrayOutputStream; javax.servlet.ServletException; javax.servlet.ServletOutputStream; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse;

public class UpdateClobExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException { response.setContentType("text/html"); String clobData = null; Connection con = null; Integer id = 1; String sourceURL = "http://fddfg:8080/JavaExample/images/large.dat"; ServletOutputStream out = response.getOutputStream(); out.println("<html><head><title>Update Clob Example</title></head>"); try { Class.forName("com.mysql.jdbc.Driver"); con =DriverManager.getConnection ("jdbc:mysql://192.168.10.59:3306/ example","root", "root"); clobData = getClobDataAsString(sourceURL); updateClob(con, id, clobData); out.println("<body><h4><font color='green'>Successfully update Your Record with id=" + id + "</font></h4></body></html>"); } catch (Exception e) { e.printStackTrace(); out.println("<body><h4><font color='red'>Unable to update " + e.getMessage() + "</font></h4></body></html>");

} } public void updateClob(Connection con, Integer id, String fileData) throws Exception{ PreparedStatement ps = null; try { ps = con.prepareStatement("update article set body = ? where id = ?"); ps.setInt(2, id); ps.setString(1, fileData); ps.executeUpdate(); }catch(Exception e){ System.out.println(e); }finally { ps.close(); } } public static String getClobDataAsString(String urlData) throws Exception { InputStream is = null; try { URL url = new URL(urlData); System.out.println("url"+url); URLConnection urlConn = url.openConnection(); urlConn.connect(); is = urlConn.getInputStream(); int BUFFER_SIZE = 1024; ByteArrayOutputStream output = new ByteArrayOutputStream(); int length; byte[] buffer = new byte[BUFFER_SIZE]; while ((length = is.read(buffer)) != -1) { output.write(buffer, 0, length); } return new String(output.toByteArray()); } finally { is.close(); } } }

Mapping of servlet (UpdateClobExample) in web.xml file:


<servlet> <servletname>UpdateClobExample</servletname> <servletclass>UpdateClobExample</servlet-

class> </servlet> <servlet-mapping> <servletname>UpdateClobExample</servletname> <urlpattern>/UpdateClobExample</urlpattern> </servlet-mapping>

Run the servlet (UpdateClobExample.java) on this url: http://localhost:8080/JavaExample/UpdateClobExample.

In case of any error in the database connection then the following error message will be displayed.

A Clob is a Character Large Object in a Database. A large character data file upto 4 GB can be stored as CLOB type.

Servlet Example To Delete Mysql Clob Data


A Clob is a Character Large Object in a Database. A large character data file upto 4 GB can be stored as CLOB type. JDBC provides java.sql.Clob interface for handling large character/text object. To delete an existing database record, which has a clob column, we can do by providing the primary key for the desired record (to be deleted). For deleting the record we

will use the "article" table wher "ID" column is the primary key, and "Body" is the CLOB column.
Mysql Clob

According to the Mysql, there are four text types TINYTEXT, TEXT, MEDIUMTEXT and LONGTEXT which can be taken as CLOB type and have the maximum lengths and storage requirements. The maximum length of TINYTEXT has 255 character (8 bits), TEXT has 16,535 character (16 bits), MEDIUMTEXT has 16,777,216 character (24 bits) and LONGTEXT has 4,294,967,295 character (32 bits).
How to define Clob Datatype in Mysql Table CREATE TABLE `article` ( `ID` int(11) NOT NULL, `Subject` varchar(256) NOT NULL, `Body` longtext, PRIMARY KEY (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 Delete Mysql Clob Data

We have developed a servlet (DeleteClobExample.java) that accepts the ID of a file and delete the associated file.
import import import import import import import import import import import import import import import import import import import java.io.*; java.util.*; javax.sql.*; javax.servlet.*; javax.servlet.http.*; java.sql.Connection; java.sql.DriverManager; java.sql.ResultSet; java.sql.SQLException; java.net.URL; java.io.IOException; java.io.InputStream; java.net.URLConnection; java.sql.PreparedStatement; java.io.ByteArrayOutputStream; javax.servlet.ServletException; javax.servlet.ServletOutputStream; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse; public class DeleteClobExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException { response.setContentType("text/html"); Connection con = null; PreparedStatement ps = null; Integer id = 1; ServletOutputStream out = response.getOutputStream(); out.println("<html><head><title>Delete Clob Example</title></head>"); try { Class.forName("com.mysql.jdbc.Driver"); con =DriverManager.getConnection ("jdbc:mysql://192.168.10.59:3306/ example", "root", "root"); ps = con.prepareStatement("delete from article where id = ?"); ps.setInt(1, id); ps.executeUpdate(); out.println("<body><h4><font color='green'>Successfully deleted clob data of id= " + id + "</font></h4></body></html>"); } catch (Exception e) { e.printStackTrace(); out.println("<body><h4><font color='red'>File could not be deleted <br><br> Exception thrown:<br> " + e.getMessage() + "</font></h4></body></html>"); }finally { try { ps.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }

Mapping of servlet (DeleteClobExample.java) in web.xml


<servlet> <servletname>DeleteClobExample</servletname> <servletclass>DeleteClobExample</servlet-class> </servlet>

<servlet-mapping> <servletname>DeleteClobExample</servletname> <urlpattern>/DeleteClobExample</urlpattern> </servlet-mapping>

Run the servlet (DeleteClobExample.java) on this url: http://localhost:8080/JavaExample/DeleteClobExample. The figure below is shown if record is deleted successfully.

and if in case any error in database connection exists or if no any file on given id then the following message will be displayed.

BLOB data in SQL is a built-in type used for storing Binary Large Object. The BLOB type stores/retreives large binary objects such as PDF files, video clips, JPEG/GIF pictures, and Microsoft word documents.

Servlet Example To Delete Mysql Blob Data


BLOB data in SQL is a built-in type used for storing Binary Large Object. The BLOB type stores/retreives large binary objects such as PDF files, video clips, JPEG/GIF pictures, and Microsoft word documents. getBlob() and setBlob() methods from interfaces like ResultSet, CallableStatement and Prepared Statement can be used to access an SQL BLOB value. The Blob

interface (java.sql.Blob) provides methods like length() to find the length of the value, position() to get the position of a pattern of bytes, getBytes() to retrieves all or part of the BLOB value as an array of bytes etc.
Creating The Table In Mysql Database: Table -------pictures Create Table ----------------------------------------CREATE TABLE `pictures` ( `id` int(11) NOT NULL auto_increment, `image` blob, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1

Using java.sql.Blob interface in servlet (DeleteBlobExample) to delete the image from existing table according to the id. In this example we show you how to delete the image from Mysql table using servlet. DeleteBlobExample.java
import import import import import import import import import import import import import java.sql.Blob; java.sql.ResultSet; java.sql.PreparedStatement; java.sql.Connection; java.io.IOException; java.io.InputStream; java.sql.SQLException; java.sql.DriverManager; javax.servlet.ServletException; javax.servlet.ServletOutputStream; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse;

public class DeleteBlobExample extends HttpServlet{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException { response.setContentType("text/html"); Connection con = null; PreparedStatement ps = null; Integer id = 9; ServletOutputStream out = response.getOutputStream(); out.println("<html><head><title>Delete Blob Example</title></head>");

try { Class.forName("com.mysql.jdbc.Driver"); con =DriverManager.getConnection ("jdbc:mysql://192.168.10.59:3306/example", "root", "root"); ps = con.prepareStatement("delete from pictures where id = '9' "); ps.setInt(1, id); ps.executeUpdate(); out.println("<body><h4><font color='green'>Successfully deleted the blob data of given id</font></h4></body></html>"); } catch (Exception e) { e.printStackTrace(); out.println("<body><h4><font color='red'>File could not be deleted. <br><br> Exception Thrown:<br> " + e.getMessage() + "</font></h4></body></html>"); }finally { try { ps.close(); con.close(); } catch (SQLException e) { e.printStackTrace(); } } } }

Mapping of servlet (DeleteBlobExample.java) in web.xml


<servlet> <servletname>DeleteBlobExample</servletname> <servletclass>DeleteBlobExample</servlet-class> </servlet> <servlet-mapping> <servletname>DeleteBlobExample</servletname> <urlpattern>/DeleteBlobExample</urlpattern> </servlet-mapping>

Run the servlet (DeleteBlobExample.java) on this url: http://localhost:8080/JavaExample/DeleteBlobExample . The data of the file will be displayed as below:

and if in case any error in database connection exists and there is no file on given id then the following message will be displayed.

This example shows how to insert CLOB data in the database. In our example, servlet InsertClobExample takes url for the CLOB data (the url will be pointing to a text file). Therefore, we will represent the CLOB as a url.

Servlet Example To Insert Mysql Clob Data


This example shows how to insert CLOB data in the database. In our example, servlet InsertClobExample takes url for the CLOB data (the url will be pointing to a text file). Therefore, we will represent the CLOB as a url.
Mysql Clob

According to the Mysql, there are four text types TINYTEXT, TEXT, MEDIUMTEXT and LONGTEXT which can be taken as CLOB type and have the maximum lengths and storage requirements. The maximum length of TINYTEXT has 255 character (8 bits), TEXT has 16,535 character (16 bits), MEDIUMTEXT has 16,777,216 character (24 bits) and LONGTEXT has 4,294,967,295 character (32 bits).

How to create Clob Data type in Mysql Table CREATE TABLE `article` ( `ID` int(11) NOT NULL, `Subject` varchar(256) NOT NULL, `Body` longtext, PRIMARY KEY (`ID`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1

The following servlet InsertClobExample shows how to insert data of CLOB type in mysql database through the servlet program. It has three variables:
y y y

id (the ID of file). fileName (the name of file) sourceURL (the url of file representing the CLOB; the servlet will open the url, construct a CLOB and insert it into the CLOB column of the article table)

Let's insert a new record with the following data in the article table:
y y y

id (1) fileName (san) sourceURL (http://localhost:8080/JavaExample/images/san.dat)

Source code of InsertClobExample.java


import import import import import import import import import import import import import import import java.io.*; java.util.*; javax.sql.*; javax.servlet.*; javax.servlet.http.*; java.sql.Connection; java.sql.DriverManager; java.sql.ResultSet; java.sql.SQLException; java.net.URL; java.io.IOException; java.io.InputStream; java.net.URLConnection; java.sql.PreparedStatement; java.io.ByteArrayOutputStream;

import javax.servlet.ServletException; import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class InsertClobExample extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException,ServletException { response.setContentType("text/html"); String clobData = null; Connection con = null; Integer id = 1; String fileName = "san"; String sourceURL = "http://localhost:8080/JavaExample/images/san.dat"; ServletOutputStream out = response.getOutputStream(); out.println("<html><head><title>Insert Clob Example</title></head>"); try { Class.forName("com.mysql.jdbc.Driver"); con =DriverManager.getConnection ("jdbc:mysql://192.168.10.59:3306/ example", "root", "root"); clobData = getClobDataAsString(sourceURL); insertClob(con, id, fileName, clobData); out.println("<body><h4><font color='green'>Successfully insert Your Record with id= " + id + "</font></h4></body></html>"); } catch (Exception e) { e.printStackTrace(); out.println("<body><h4><font color='red'>Unable to insert " + e.getMessage() + "</font></h4></body></html>"); } } public void insertClob(Connection con, Integer id, String fileName, String fileData)throws Exception{ PreparedStatement ps = null; try { ps = con.prepareStatement("insert into article(id, subject, body) values (?, ?, ?)"); ps.setInt(1, id); ps.setString(2, fileName); ps.setString(3, fileData); ps.executeUpdate(); }catch(Exception e){ System.out.println(e); }finally { ps.close(); } } public static String getClobDataAsString(String urlData) throws Exception { InputStream is = null;

try { URL url = new URL(urlData); System.out.println("url"+url); URLConnection urlConn = url.openConnection(); urlConn.connect(); is = urlConn.getInputStream(); int BUFFER_SIZE = 1024; ByteArrayOutputStream output = new ByteArrayOutputStream(); int length; byte[] buffer = new byte[BUFFER_SIZE]; while ((length = is.read(buffer)) != -1) { output.write(buffer, 0, length); } return new String(output.toByteArray()); } finally { is.close(); } } }

Mapping of servlet (InsertClobExample.java) in web.xml file:


<servlet> <servletname>InsertClobExample</servletname> <servletclass>InsertClobExample</servlet-class> </servlet> <servlet-mapping> <servletname>InsertClobExample</servletname> <url-pattern>/InsertClobExample</urlpattern> </servlet-mapping>

Run the servlet (InsertClobExample.java) on this url: http://localhost:8080/JavaExample/InsertClobExample.

In case of any error in the database connection then the following error message will be displayed.

This example shows how to retrieve date from existing table of MySql database. Date functions can be used in the SELECT statement or in the WHERE clause of a Query.

GET DATE in JDBC


This example shows how to retrieve date from existing table of MySql database. Date functions can be used in the SELECT statement or in the WHERE clause of a Query. Various date functions of Date areADDDATE() This function is used for add date to any other date. ADDTIME() This function is used for add time. CURDATE(), CURRENTDATE(), CURRENTDATE These three are synonyms, are used for display the current date. CURRENTTIME(), CURRENTTIME, CURTIME() These are same used for current time. DATE_ADD() This is used for adding two dates. DATEDIFF() This is used for subtraction of two dates.

DAY(), DAYOFMONTH() It shows the day of month from 1 to 31. DAYNAME() It shows the name of the weekday. DAYOFWEEK() It returns the index of weekdays. DAYOFYEAR() It returns the day of year from 1 to 366. LASTDAY() It returns the last day of the month. LOCALTIME(),LOCALTIMESTAMP(),NOW() It returns the current date and time. MONTH() It returns the month from the date has gone. MONTHNAME() It returns the name of the month. SECOND() It returns the seconds from 0 to 59. STR_TO_DATE() It converts a string to a date. SYSDATE() It returns the time of execution the function. TIMEDIFF() It returns the diffrence of time. WEEK() It returns the week number. WEEKDAY() It returns the weekday index. WEEKOFYEAR() It returns the week of year from 1 to 53.

YEAR() It returns the year. YEARWEEK() It returns the year and week. GetDate.java
import java.sql.*; import java.io.*; public class GetDate { public static void main(String a[]) { Connection con = null; String url = "jdbc:mysql://lacalhost:3306/"; String dbName = "vineej"; String driver = "com.mysql.jdbc.Driver"; String userName = "vineej"; String password = "no"; try { Class.forName(driver).newInstance(); con = DriverManager.getConnection (url+dbName,userName,password); Statement st = con.createStatement(); ResultSet rs= st.executeQuery("select Dates from Student where Name ='Ravi'"); while(rs.next()) { String data = rs.getString(1); System.out.println(data); } System.out.println("Results"); st.close(); } catch( Exception e ) { System.out.println(e.getMessage()); e.printStackTrace(); } } }

Description of the Program This program is concern with retrieve the date from existing table in the database. Student is the of a table and ravi is the name of a student. Dates is the field in table from where we can retrieve the date.When the query successfully executed it will shows "Results". Description of code 1.First in the program we import the java.sql and java.io packages then define the GetDate class. import java.sql.*; import

java.io.*; 2.Create a connection with MySql database con = DriverManager.getConnection(url+dbName,userName,password); 3.Create statement and then execute query with the SELECT statement. Statement st = con.createStatement(); ResultSet rs = st.executeQuery("select Dates from Student where Name ='Ravi"); 4.Finally got the result by the getString() method. while( rs.next() ) { String data = rs.getString(1); System.out.println( data ); } 5. After all connection should be closed. con.close(); 6. printStackTrace() method The method is used to show error messages. If the connection is not connected then it throws the exception and print the message.
This is detailed java program to connect java application and execute sql query like create table in mysql database, insert some values and retrieve values from the table.

Create table and insert data by sql query


This is detailed java program to connect java application and execute sql query like create table in mysql database, insert some values and retrieve values from the table. Before running this java code you need mysql-connector-java-3.1.6-bin.jar file in the jdk1.6.0_01\lib and set class path to this file.

ExecuteSqlQuery.java
/** * Execute sql queries with java application. */ import java.sql.*; class ExecuteSqlQuery { public static void main(String[] args) { try { /* Create string of connection url within specified format with machine name, port number and database name. Here machine name id localhost and database name is usermaster. */ String connectionURL = "jdbc:mysql://localhost:3306/usermaster"; // declare a connection by using Connection interface Connection connection = null; // declare object of Statement interface that uses for executing sql statements. Statement statement = null; // declare a resultset that uses as a table for output data from tha table. ResultSet rs = null; int updateQuery = 0; // Load JDBC driver "com.mysql.jdbc.Driver". Class.forName("com.mysql.jdbc.Driver").newInstance(); /* Create a connection by using getConnection() method that takes parameters of string type connection url, user name and password to connect to database. */ connection = DriverManager.getConnection(connectionURL, "root", "root"); /* createStatement() is used for create statement object that is used for sending sql statements to the specified database. */ statement = connection.createStatement(); // sql query of string type to create a data base. String QueryString = "CREATE TABLE user_master1(User_Id INTEGER NOT NULL AUTO_INCREMENT, " + "User_Name VARCHAR(25), UserId VARCHAR(20), User_Pwd VARCHAR(15), primary key(User_Id))"; updateQuery = statement.executeUpdate(QueryString); // sql query to insert values in the specified table. QueryString = "INSERT INTO user_master1(User_Name,UserId,User_Pwd) VALUES ('Mahendra',"+ "'mahendra25','1213456')"; updateQuery = statement.executeUpdate(QueryString); if (updateQuery != 0) { System.out.println("table is created successfully and " + updateQuery + " row is inserted."); } // sql query to retrieve values from the specified table. QueryString = "SELECT * from user_master1"; rs = statement.executeQuery(QueryString); while (rs.next()) { System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3) + " "+rs.getString(4)+"\n"); } // close all the connections. rs.close(); statement.close();

connection.close(); } catch (Exception ex) { System.out.println("Unable to connect to batabase."); } } }

Output of the program

This is detailed simple java code that how save image into mysql database. Before running this java code you need to create data base and table to save image in same database.

Insert Image into Mysql Database through Simple Java Code


This is detailed simple java code that how save image into mysql database. Before running this java code you need to create data base and table to save image in same database. In the example given below we have used database 'mahendra' and table 'save_image'.

Structure of table 'save_image'


First create database named 'mahendra' by query given below: mysql> create database mahendra; and create table by query given below:
CREATE TABLE save_image ( id int(5) NOT NULL auto_increment, name varchar(25) default NULL, city varchar(20) default NULL,

image blob, Phone varchar(15) default NULL, PRIMARY KEY (`id`) );

Save table 'save_image' in database 'mahendra'. Before running this java code you need mysql connector jar in the jdk1.6.0_01./lib. SaveImageToDatabase java file provides full code for uploading image in database. SaveImageToDatabase.java
import java.sql.*; import java.io.*; class SaveImageToDatabase { public static void main(String[] args) throws SQLException { // declare a connection by using Connection interface Connection connection = null; /* Create string of connection url within specified format with machine name, port number and database name. Here machine name id localhost and database name is mahendra. */ String connectionURL = "jdbc:mysql://localhost:3306/mahendra"; /*declare a resultSet that works as a table resulted by execute a specified sql query. */ ResultSet rs = null; // Declare prepare statement. PreparedStatement psmnt = null; // declare FileInputStream object to store binary stream of given image. FileInputStream fis; try { // Load JDBC driver "com.mysql.jdbc.Driver" Class.forName("com.mysql.jdbc.Driver").newInstance(); /* Create a connection by using getConnection() method that takes parameters of string type connection url, user name and password to connect to database. */ connection = DriverManager.getConnection(connectionURL, "root", "root"); // create a file object for image by specifying full path of image as parameter. File image = new File("C:/image.jpg"); /* prepareStatement() is used for create statement object that is used for sending sql statements to the specified database. */

psmnt = connection.prepareStatement ("insert into save_image(name, city, image, Phone) "+ "values(?,?,?,?)"); psmnt.setString(1,"mahendra"); psmnt.setString(2,"Delhi"); psmnt.setString(4,"123456"); fis = new FileInputStream(image); psmnt.setBinaryStream(3, (InputStream)fis, (int)(image.length())); /* executeUpdate() method execute specified sql query. Here this query insert data and image from specified address. */ int s = psmnt.executeUpdate(); if(s>0) { System.out.println("Uploaded successfully !"); } else { System.out.println("unsucessfull to upload image."); } } // catch if found any exception during rum time. catch (Exception ex) { System.out.println("Found some error : "+ex); } finally { // close all the connections. connection.close(); psmnt.close(); } } }

Output of the program:

In this section we will see how to delete row and column from given table through java code.

Delete row and column from table through java code


In this section we will see how to delete row and column from given table through java code. Java code create connection between program and database by using connection interface and jdbc driver.

In this example given below we have a database named 'student' and a table 'stu_info' in same database. Structure of table 'stu_info' is as following.....

create table stu_info ( ID int not null auto_increment, Name varchar(20), Address varchar(20), Phone int(15), primary key(ID) ); Table: +----+----------+-----------+---------+ | ID | Name | Phone | Address | +----+----------+-----------+---------+ | 11 | Mahendra | 9990254913 | Delhi | | 12 | Mahendra | 9990254913 | Delhi | | 13 | Mahendra | 9990254913 | Delhi | +----+----------+-----------+---------+

In this table we will delete the row having minimum value of ID then delete the column named 'Address'. Before running this java code you need to paste a .jar file named mysql connector.jar in the jdk1.6.0_01\lib
import java.sql.*; import java.io.*; class ConnectToDatabase { public static void main(String[] args) throws SQLException { // declare a connection by using Connection interface Connection connection = null; /* Create string of connection url within specified format with machine name, port number and database name. Here machine name id localhost and database name is student. */ String connectionURL = "jdbc:mysql://localhost:3306/student"; /*declare a resultSet that works as a table

resulted by execute a specified sql query. */ ResultSet rs = null; // Declare statement. Statement statement = null; try { // Load JDBC driver "com.mysql.jdbc.Driver". Class.forName("com.mysql.jdbc.Driver").newInstance(); /* Create a connection by using getConnection() method that takes parameters of string type connection url, user name and password to connect to database. */ connection = DriverManager.getConnection(connectionURL, "root", "root"); /* createStatement() is used for create statement object that is used for sending sql statements to the specified database. */ statement = connection.createStatement(); /* executeQuery() method execute specified sql query. Here this query checks number of rows present in table */ rs = statement.executeQuery("select* from stu_info"); int count = 0; while(rs.next()) { count++; } System.out.println("Number of Rows present in table : "+count); /* Here sql query find the element from the table havinf minimum ID */ rs = statement.executeQuery("select min(ID) from stu_info"); rs.next(); // This sql query delete the row having minimum ID. statement.executeUpdate("delete from stu_info where ID='"+rs.getInt(1)+"'"); System.out.println("Row is deleted successfully."); /* Here this query checks number of rows present in table after deletion */ int count1 = 0;

rs = statement.executeQuery("select* from stu_info"); while(rs.next()) { count1++; } System.out.println("after deletion number of Rows present in table : "+count1); // Here this query shows column names present in table. rs = statement.executeQuery("show COLUMNS from stu_info"); System.out.println("Columns in table 'stu_info' of database 'student' : "); while(rs.next()) { System.out.println(rs.getString("Field")); } // This sql query delete the column name of specified name. statement.executeUpdate("ALTER TABLE stu_info DROP Address"); System.out.println("column 'Address' is deleted successfully."); // Again this query shows column names present in table. rs = statement.executeQuery("show COLUMNS from stu_info"); System.out.println("after deletion columns in table ' stu_info' of database 'student' : "); while(rs.next()) { System.out.println(rs.getString("Field")); } } // catch exceptions if found any exception at run time. catch(Exception ex){ System.out.println("Sorry ! found some problems with database."); System.out.println("Error is : "+ ex); } finally { // close all the connections. rs.close(); statement.close(); connection.close(); } } }

Save this java code with class name and .java extension then compile from command prompt with javac command.

In this Tutorial we want to describe you a code that helps you to understand Jdbc Connection Url.

JDBC ConnectionUrl
The JDBC Connection Url is the mean of connecting a front end application made in java platform to backend database. An object of Connection enables your application to connect database. This all requires a SQL queries to execute and return the result over that connection object. Simlararly,In this Tutorial we want to describe you an example that helps you to understand JDBC Connection url. The code describe you the JDBC Connection between url and a database. Understand with Example The package java.sql.* is to be imported, that include all the set of defined classes provides you a network interface between url and database. Here we have a class JdbcConnectionUrl. Inside this class, we have a main method( ) contains a declared list of objects and variable. Now you can see the uses of declared variable in the given below code Loading Database Driver: loading of a driver class that invokes Class.forName( ) with the Driver class name passed as an argument. Once the driver is loaded ,you can connect the Java front end application to the backend database. In case the exception occurred in loading a database inside the try block. The catch block handle the exception and println print the exception. Driver Manager.getConnection ( ) :This method return you a connection object that built your path between url and database. The Println print the connection url from the variable string url and db.

st = con.createconnection( ) :This method return you an sql object. Once connection is established ,your front-end application is able to interact with backend database. A connection object enables you to send and execute SQL Statement to a backend database. rs = st.executequery(sql) : This method return you result set object that accept sql query as parameter.The value retrieved from it is assigned in result set rs.The retrieved table row contain a element in sequence. next( ) :The next method is used to retrieve successively element through the rows from a result set. Finally the JDBC Connection url is built and println print the url and db,first name and last name from the result set obtained from database.

JdbcConnectionUrl .java
import java.sql.*; public class JdbcConnectionUrl { public static void main(String args[]) { Connection con = null; Statement st = null; ResultSet rs = null; String url = "jdbc:mysql://localhost:3306/"; String db = "komal"; String driver = "com.mysql.jdbc.Driver"; String user = "root"; String pass = "root"; try { Class.forName(driver); con = DriverManager.getConnection(url + db, user, pass); System.out.println("Connection url : "+url + db); st = con.createStatement(); String sql = "select * from customer"; rs = st.executeQuery(sql); System.out.println("First Name \tLast Name"); while (rs.next()) { System.out.print(rs.getString("First_Name") + " System.out.println(rs.getString("Last_Name")); } } catch (Exception e) { System.out.println(e); } } }

\t");

Output
Connection url : jdbc:mysql://localhost:3306/komal

First Name girish mahendra komal yogesh pinku deepak

Last Name tewari singh singh pandey tripathi tripathi In this Tutorial we want to describe you a code that helps you in understanding a Jdbc Connection.

JDBC connection
The JDBC connection implements a connection with database in front end application. The JDBC includes execution of SQL queries return a result set over that specified connection. Understand with Example In last Tutorial we illustrates you JDBC url connection. The current Tutorial helps you to understand JDBC connection. The code explains you how creating and closing of connection is done. For this program code we have a class Jdbc Connection, We have a list of method required to connect and close the connection. Before the implementation of class we need to import a package java.sql.* needed for network interface between url and back end. Loading a driver is done by calling a class.forName ( ) and accept the driver class as argument. DriverManager.getConnection ( ) :This method returns you an connection object.DriverManager.getConnection built a connection with database. Using this method we establish a connection between url and database. Once the connection is built,println print the connection is created con.close ( ) : An object of connection is used to close the connection between database and url. Finally the println print the connection is closed.In case there is an exception in try block, during the establishment of connection between the front end in java application(url) and backend. The catch block is responsible for handling the exception. JdbcConnection.java

import java.sql.*; public class JdbcConnection { public static void main(String args[]) {

Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String db = "komal"; String driver = "com.mysql.jdbc.Driver"; String user = "root"; String pass = "root"; try { Class.forName(driver); con = DriverManager.getConnection(url + db, user, pass); System.out.println("jdbc driver for mysql : " + driver); System.out.println("Connection url : " + url + db); System.out.println("Connection is created..."); con.close(); System.out.println("Connection is closed..."); } catch (Exception e) { System.out.println(e); } } }

Output
Connection is created... Connection is closed...

JDBC is simply a Java Database Connectivity. This Connectivity provides you an API, that provides you to interact your Java Application in your front end with the backend.

JDBC batch
JDBC is simply a Java Database Connectivity. This Connectivity provides you an API, that provides you to interact your Java Application in your front end with the backend. The backend can be SQL-2000,2005,MySql. A batch in JDBC is a set of sql statement altogether to the database for execution. Understand with Example We have already know with the JDBC Connection in previous tutorial. In this Tutorial we want to describe you a code that helps you in understanding a JDBC batch. The code explain you a JDBC,that include collective set of SQL queries executed altogether to the database. For this we define a class JdbcBatch, Inside the main method, we define a url,database,driver name,username and password that helps you to establish a connection an application with the backend database. The list of method helps you in execution of JDBC batch are as given below Before defining a class, you need to import a java.sql.* :The package import all defined classes, which are required for providing network interface between the application and database.

Driver loading : load the driver class by calling a Class.forName ( ) with the driver passed as an argument. Driver Connection provides you to connect the front end in java application and backend in sql. con = DriverManager.getConnection(url+db,user,pass) -The.getConnection ( ) return you an object of connection class.This method attempt to connect a database connection to the specified url. The create Statement ( ) method return you an object of statement. An statement is used to execute a sql statement in the backend add Batches( ) : An object of statement call a add Batches ( ) method, that set the batch values into specified database. st.executeBatches ( ) :This method is used to execute the sql Batches. execute Query ( ) - This method return you an object of result set. This object include set of all the values from the table "stu". The next ( ) return you the successive element from a table of the database.Finally the println print the element stored in the database. JdbcBatch .java
import java.sql.*; public class JdbcBatch { public static void main(String args[]) { Connection con = null; Statement st = null; ResultSet rs = null; String url = "jdbc:mysql://localhost:3306/"; String db = "komal"; String driver = "com.mysql.jdbc.Driver"; String user = "root"; String pass = "root"; try { Class.forName(driver); con = DriverManager.getConnection(url + db, user, pass); //con.setAutoCommit(false);// Disables auto-commit. st = con.createStatement(); st.addBatch("INSERT INTO stu " + "VALUES('1','name2')"); st.addBatch("INSERT INTO stu " + "VALUES('2','name3')"); st.addBatch("INSERT INTO stu " + "VALUES('3','name4')"); st.executeBatch(); String sql = "select * from stu "; rs = st.executeQuery(sql); System.out.println("No \tName"); while (rs.next()) { System.out.print(rs.getString(1) + "

\t");

System.out.println(rs.getString(2)); } rs.close(); st.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } } }

Output
No 4 5 6 Name Komal Ajay Santosh

In this Tutorial we want to describe you a code that helps you in understand Jdbc batch insert.

JDBC batch insert


JDBC Batch Insert is a set of SQL Statements sent to the database and executed as a single unit. The Statement object performs the batch update. Understand with Example The Tutorial depicts you an example from JDBC Batch Insert, An empty array object is linked, whenever a statement object is created. The multiple SQL statements is added to the empty array. This statements is executed as a batch. The con.setAutoCommit( ) is used to disable the auto commit.The batch contain three SQL INSERT statement added to a batch using the addBatch ( ).The code show you the list of method required to carry out JDBC Batch Insert are as follows Driver loading - Once the sql package is imported, the second step is the loading of a driver class that call a forclass.name with driver name passed as argument. Once your driver is loaded you connect your front end java application to the backend database. If there is an exception in try block, the catch block subsequently handle the exception. DriverManager.getconnection ( ) : This is used to establish a connection between database and respective url. . con.createStatement ( ) : This is used to provide you a Sql object. On establishing a connection ,your application can interact with backend database. An connection object is used to send and execute Sql statement to a backend database. st.addbatch( ) : This method is used to add the sql parameter to the batch of command.

executeQuery ( ) : This method is used to return the value obtained from select command and is stored in result set object.rs.next( ) - This method is used to retrieve the element from a database in successively sequence. The print ln print the element from rs.getString ( ),which return you the value of elements from the database. JdbcBatchInsert.java
import java.sql.*; public class JdbcBatchInsert { public static void main(String args[]) { Connection con = null; Statement st = null; ResultSet rs = null; String url = "jdbc:mysql://localhost:3306/"; String db = "komal"; String driver = "com.mysql.jdbc.Driver"; String user = "root"; String pass = "root"; try { Class.forName(driver); con = DriverManager.getConnection(url + db, user, pass); con.setAutoCommit(false);// Disables auto-commit. st = con.createStatement(); st.addBatch("INSERT INTO person VALUES('4','Komal')"); st.addBatch("INSERT INTO person VALUES('5','Ajay')"); st.addBatch("INSERT INTO person VALUES('6','Santosh')"); st.executeBatch(); String sql = "select * from person"; rs = st.executeQuery(sql); System.out.println("No \tName"); while (rs.next()) { System.out.print(rs.getString(1) + " \t"); System.out.println(rs.getString(2)); } rs.close(); st.close(); con.close(); } catch (Exception e) { e.printStackTrace(); } } }

Output
No 4 5 6 Name Komal Ajay Santosh

S-ar putea să vă placă și