







Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
A comprehensive overview of jdbc (java database connectivity), a java api for connecting and interacting with databases. It covers key concepts, including jdbc drivers, connection establishment, statement execution, and batch processing. The document also explores the advantages and disadvantages of different jdbc driver types, such as odbc bridge drivers, native-api drivers, network protocol drivers, and thin drivers. It further delves into the functionality of the drivermanager class, connection interface, statement interface, preparedstatement interface, and resultset interface, highlighting their roles in database interaction. The document concludes with a practical example of batch processing in jdbc, demonstrating its efficiency in executing multiple queries.
Typology: Lecture notes
1 / 13
This page cannot be seen from the preview
Don't miss anything!








This unit deals with the general descriptions of database system, SQL and JDBC (java database connectivity). These contents will be delivered to the students through brain storming, group discussion, observation/demonstration, and mini lecture and students assessed with lab exercise, group work and individual lab assignment. Objectives: At the end of this unit, the students will be able to Define database and SQL K L, Explain concepts of JDBC K L, Construct a certain java application using JDBC A L, Contents Define database, SQL and JDBC Concepts of JDBC programming Installation and setting of JDBC Executing database quires Method of teaching Brain storming Mini lecture Group discussion Lab work Brainstorming: What is database, what are the best ways to store data permanently? 6.2. INTRODUCTION JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the database. There are four types of JDBC drivers:
We will discuss the above four drivers in the types of JDBC driver lesson. We can use JDBC API to access tabular data stored in any relational database. By the help of JDBC API, we can save, update, delete and fetch data from the database. The current version of JDBC is 4.3. It is the stable release since 21 September 2017. The java.sql package contains classes and interfaces for JDBC API. A list of popular interfaces of JDBC API are given below: ❖ Driver interface ❖ Connection interface ❖ Statement interface ❖ PreparedStatement interface ❖ CallableStatement interface ❖ ResultSet interface ❖ ResultSetMetaData interface ❖ DatabaseMetaData interface ❖ RowSet interface A list of popular classes of JDBC API are given below: ❖ DriverManager class ❖ Blob class ❖ Clob class ❖ Types class 6.3. WHY SHOULD WE USE JDBC Before JDBC, ODBC API was the database API to connect and execute the query with the database. However, ODBC API uses ODBC driver, which is written in C language (i.e. platform dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language). We can use JDBC API to handle database using Java program and can perform the following activities:
Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge. Advantages: ❖ easy to use. ❖ can be easily connected to any database. Disadvantages: ❖ Performance degraded because JDBC method call is converted into the ODBC function calls. ❖ The ODBC driver needs to be installed on the client machine. 2) Native-API driver The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in java. Advantage: ❖ Performance upgraded than JDBC-ODBC bridge driver. Disadvantage: ❖ The Native driver needs to be installed on each client machine. ❖ The Vendor client library needs to be installed on the client machine.
3) Network Protocol driver The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java. Advantage: ❖ No client side library is required because of application server that can perform many tasks like auditing, load balancing, logging etc. Disadvantages: ❖ Network support is required on client machines. ❖ Requires database-specific coding to be done in the middle tier. ❖ Maintenance of Network Protocol drivers becomes costly because it requires database-specific coding to be done in the middle tier. 4) Thin driver The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin driver. It is fully written in Java language.
Here, the Java program is loading a MySQL driver to establish database connection. Class.forName("com.mysql.jdbc.Driver"); 2) Create the connection object The getConnection() method of DriverManager class is used to establish connection with the database. Syntax of getConnection() method 1 ) public static Connection getConnection(String url) throws SQLException 2 ) public static Connection getConnection(String url,String name,String password) throws SQLException Example to establish connection with the MySQL database Connection con=DriverManager.getConnection( "jdbc:mysql://localhost","root","admin123**"); where jdbc is the API, MySQL is the database, localhost is the server name on which MySQL is running, we may also use IP address. The default username for the MySQL database is root. **admin123**** is the password given by the user at the time of installing the MySQL database. 3) Create the Statement object The createStatement() method of the Connection interface is used to create a statement. The object of statement is responsible to execute queries with the database. Syntax of createStatement() method public Statement createStatement() throws SQLException Example to create the statement object Statement stmt=con.createStatement();
4) Execute the query The executeQuery() method of Statement interface is used to execute queries to the database. This method returns the object of ResultSet that can be used to get all the records of a table. Syntax of executeQuery() method public ResultSet executeQuery(String sql) throws SQLException Example to execute query ResultSet rs=stmt.executeQuery("select * from emp"); while (rs.next()){ System.out.println(rs.getInt( 1 )+" "+rs.getString( 2 )); } 5) Close the connection object By closing the connection object statement and ResultSet will be closed automatically. The close() method of the Connection interface is used to close the connection. Syntax of close() method public void close() throws SQLException Example to close connection con.close(); Note: Since Java 7, JDBC has the ability to use try-with-resources statements to automatically close resources of type Connection, ResultSet, and Statement. It avoids explicit connection closing steps.
Comm only used methods of Statement interface: The important methods of Statement interface are as follows: 1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of ResultSet. 2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert, update, delete etc. 3) public boolean execute(String sql): is used to execute queries that may return multiple results. 4) public int[] executeBatch(): is used to execute batch of commands. ResultSet interface The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to before the first row. By default, the ResultSet object can be moved forward only and it is not updatable. But we can make this object to move forward and backward direction by passing either TYPE_SCROLL_INSENSITIVE or TYPE_SCROLL_SENSITIVE in createStatement(int,int) method as well as we can make this object as updatable by: Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); Commonly used methods of ResultSet interface The Statement interface provides methods to execute queries with the database. The statement interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
PreparedStatement interface The PreparedStatement interface is a subinterface of Statement. It is used to execute parameterized query. Let's see the example of parameterized query: String sql="insert into emp values(?,?,?)"; As you can see, we are passing parameter (?) for the values. Its value will be set by calling the setter methods of PreparedStatement. Why use PreparedStatement? Improves performance : The performance of the application will be faster if you use PreparedStatement interface because query is compiled only once. How to get the instance of PreparedStatement? The prepareStatement() method of the Connection interface is used to return the object of PreparedStatement. Syntax: public PreparedStatement prepareStatement(String query) throws SQLException{}
❖ Create Statement ❖ Add query in the batch ❖ Execute Batch ❖ Close Connection Nota Bene : - Refer to a book entitled “ Java How to Program Tenth edition ” from page number 1087 to 1140 and do the Self-Review Exercise located on page 1146 to 1148. It is available in the technology library.