Download JDBC and UML Overview: Java Database Connectivity and Software Modeling and more Study notes Law in PDF only on Docsity!
Introduction to JDBC (Java Database
Connectivity)
- JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the database.It provides the language with Java database connectivity standards. It is used to write programs required to access databases. JDBC, along with the database driver, can access databases and spreadsheets. The enterprise data stored in a relational database(RDB) can be accessed with the help of JDBC APIs.
Definition of JDBC(Java Database Connectivity)
JDBC is an API(Application programming interface) used in Java programming to interact with databases. The classes and interfaces of JDBC allow the application to send requests made by users to the specified database. The current version of JDBC is JDBC 4.3, released on 21st September 2017.
Components of JDBC
four main components of JDBC through which it can interact with a database.
1. JDBC API: It provides various methods and interfaces for easy communication with the database. It provides two packages as follows, which contain the java SE and Java EE platforms to exhibit WORA(write once run anywhere) capabilities. The java.sql package contains interfaces and classes of JDBC API. java.sql: This package provides APIs for data access and data process in a relational database, It also provides a standard to connect a database to a client application. 2. JDBC Driver manager: It loads a database-specific driver in an application to establish a connection with a database. It is used to make a database-specific call to the database to process the user request. 3. JDBC Test suite: It is used to test the operation(such as insertion, deletion, updation) being performed by JDBC Drivers. 4. JDBC-ODBC Bridge Drivers : It connects database drivers to the database. This bridge translates the JDBC method call to the ODBC function call. It makes use of the sun.jdbc.odbc package which includes a native library to access ODBC characteristics.
Architecture of JDBC
Description:
- Application: It is a java applet or a servlet that communicates with a data source.
- The JDBC API: The JDBC API allows Java programs to execute SQL statements and retrieve results. Some of the important classes and interfaces defined in JDBC API are as follows:
- DriverManager: It plays an important role in the JDBC architecture. It uses some database-specific drivers to effectively connect enterprise applications to databases.
- JDBC drivers: To communicate with a data source through JDBC, you need a JDBC driver that intelligently communicates with the respective data source
Advantages
- This driver software is built-in with JDK so no need to install separately.
- It is a database independent driver.
Disadvantages
- As a common driver is used in order to interact with different databases, the data transferred through this driver is not so secured.
- The ODBC bridge driver is needed to be installed in individual client machines.
- Type- 1 driver isn’t written in java, that’s why it isn’t a portable driver.
2. Native-API driver – Type 2 driver ( Partially Java driver)
The Native API driver uses the client - side libraries of the database. This driver converts JDBC method calls into native calls of the database API. In order to interact with different database, this driver needs their local API, that’s why data transfer is much more secure as compared to type-1 driver. This driver is not fully written in Java that is why it is also called Partially Java driver.
Advantage
- Native-API driver gives better performance than JDBC-ODBC bridge driver.
Disadvantages
- Driver needs to be installed separately in individual client machines
- The Vendor client library needs to be installed on client machine.
- Type- 2 driver isn’t written in java, that’s why it isn’t a portable driver
- It is a database dependent driver.
3. Network Protocol driver – Type 3 driver (fully Java driver)
The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. Here all the database connectivity drivers are present in a single server, hence no need of individual client-side installation.
Advantages
- Type- 3 drivers are fully written in Java, hence they are portable drivers.
- No client side library is required because of application server that can perform many tasks like auditing, load balancing, logging etc.
- Switch facility to switch over from one database to another database.
Disadvantages
- Network support is required on client machine.
- Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be done in the middle tier.
4. Thin driver – Type 4 driver (fully Java driver)
Type-4 driver is also called native protocol driver. This driver interact directly with database. It does not require any native database library, that is why it is also known as Thin Driver.
Steps for connectivity between Java program and database
1. Loading the Driver To begin with, you first need load the driver or register it before using it in the program. Registration is to be done once in your program. You can register a driver in one of two ways mentioned below :
- Class.forName() :.The following example uses Class.forName() to load the Oracle driver – Class.forName(“oracle.jdbc.driver.OracleDriver”);
- DriverManager.registerDriver():The following example uses DriverManager.registerDriver()=DriverManager.registerDriver(neworacle.jdbc.driver.O racleDriver()) 2. Create the connections After loading the driver, establish connections using : Connection con = DriverManager.getConnection(url,user,password) user – username from which your sql command prompt can be accessed. password – password from which your sql command prompt can be accessed. con: is a reference to Connection interface. url : Uniform Resource Locator. It can be created as follows: String url = “ jdbc:oracle:thin:@localhost:1521:xe” 3. Create a statement Once a connection is established you can interact with the database. The JDBCStatement, CallableStatement, and PreparedStatement interfaces define the methods that enable you to send SQL commands and receive data from your database. 4. Execute the query The executeQuery() method of Statement interface is used to execute queries of retrieving values from the database. This method returns the object of ResultSet that can be used to get all the records of a table
Statements in JDBC There are three types of statements in JDBC namely, Statement, Prepared Statement, Callable statement.
Statement
The Statement interface represents the static SQL statement.
It helps you to create a general purpose SQL statements using
Java.
Creating a statement
You can create an object of this interface using the createStatement() method of the Connection interface. Create a statement by invoking the createStatement() method as shown below. Statement stmt = null; try { stmt = conn.createStatement( );
.. .} catch (SQLException e) { .. .} finally { .. .}
Executing the Statement object
Once you have created the statement object you can execute it using one of the execute methods namely, execute(), executeUpdate() and, executeQuery().
- execute(): This method is used to execute SQL DDL statements, it returns a boolean value specifying whether the ResultSet object can be retrieved.DDL
- executeUpdate(): This method is used to execute statements such as insert, update, delete. It returns an integer value representing the number of rows affected.DML
- executeQuery(): This method is used to execute statements that returns tabular data (example SELECT statement). It returns an object of the class ResultSet .DQL
Executing the Prepared Statement
Once you have created the PreparedStatement object you can execute it using one of the execute() methods of the PreparedStatement interface namely, execute(), executeUpdate() and, executeQuery().
- execute(): This method executes normal static SQL statements in the current prepared statement object and returns a boolean value.
- executeQuery(): This method executes the current prepared statement and returns a ResultSet object.
- executeUpdate(): This method executes SQL DML statements such as insert update or delete in the current Prepared statement. It returns an integer value representing the number of rows affected.
CallableStatement
The CallableStatement interface provides methods to execute stored procedures. Since the JDBC API provides a stored procedure SQL escape syntax, you can call stored procedures of all RDBMS in a single standard way.
Creating a CallableStatement
You can create an object of the CallableStatement (interface) using the prepareCall() method of the Connection interface. This method accepts a string variable representing a query to call the stored procedure and returns a CallableStatement object. A CallableStatement can have input parameters or, output parameters or, both. To pass input parameters to the procedure call you can use place holder and set values to these using the setter methods (setInt(), setString(), setFloat()) provided by the CallableStatement interface.
By default, ResultSet object can be moved forward only and it is not updatable.
Setting values to the input parameters
You can set values to the input parameters of the procedure call using the setter methods. These accept two arguments one is an integer value representing the placement index of the input parameter and the other is an int or, String or, float etc… representing the value you need to pass an input parameter to the procedure. Instead of index you can also pass the name of the parameter in String format.
Executing the Callable Statement
Once you have created the CallableStatement object you can execute it using one of the execute() method. cstmt.execute(); ResultSet interface The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to before the first row. 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 1) public boolean next(): is used to move the cursor to the one row next from the current position. 2) public boolean previous(): is used to move the cursor to the one row previous from the current position. 3) public boolean first(): is used to move the cursor to the first row in result set object.
Commonly used methods of ResultSetMetaData interface
Method Description public int getColumnCount()throws SQLException it returns the total number of columns in the ResultSet object. public String getColumnName(int index)throws SQLException it returns the column name of the specified column index. public String getColumnTypeName(int index)throws SQLException it returns the column type name for the specified index. public String getTableName(int index)throws SQLException it returns the table name for the specified column index. How to get the object of ResultSetMetaData: The getMetaData() method of ResultSet interface returns the object of ResultSetMetaData. Syntax: public ResultSetMetaData getMetaData() throws SQLException
Java Networking Terminology
In Java Networking, many terminologies are used frequently. These widely
used Java Networking Terminologies are given as follows:
1. IP Address – An IP address is a unique address that distinguishes a
device on the internet or a local network. IP stands for “Internet
Protocol.” It comprises a set of rules governing the format of data sent
via the internet or local network. IP Address is referred to as a logical
address that can be modified. It is composed of octets. The range of
each octet varies from 0 to 255.
o Range of the IP Address – 0.0.0.0 to 255.255.255.
o For Example – 192.168.0.
2. Port Number – A port number is a method to recognize a particular
process connecting internet or other network information when it
reaches a server. The port number is used to identify different
applications uniquely. The port number behaves as a communication
endpoint among applications. The port number is correlated with the
IP address for transmission and communication among two
applications. There are 65,535 port numbers, but not all are used
every day.
3. Protocol – A network protocol is an organized set of commands that
define how data is transmitted between different devices in the same
network. Network protocols are the reason through which a user can
easily communicate with people all over the world and thus play a
critical role in modern digital communications. For Example – TCP,
FTP, POP, etc.
4. MAC Address – MAC address stands for Media Access Control
address. It is a bizarre identifier that is allocated to a NIC (Network
Interface Controller/ Card). It contains a 48 bit or 64-bit address, which
is combined with the network adapter. MAC address can be in
hexadecimal composition. In simple words, a MAC address is a unique
number that is used to track a device in a network.
5. Socket – A socket is one endpoint of a two-way communication
connection between the two applications running on the network. The
socket mechanism presents a method of inter-process communication
(IPC) by setting named contact points between which the
communication occurs. A socket is tied to a port number so that the TCP
S No . Method Description static InetAddress getByAddress(byte[] 1 addr) This method is used to return an object of the InetAddress class provided the raw IP address. static InetAddress getByAddress(String 2 host, byte[] addr) This method is used to create an InetAddress based on the given hostname and IP address. static InetAddress getByName(String 3 host) This method is used to determine the IP address of a host when the host’s name is given. static InetAddress InetAddress 4 getLocalHost() This method is used to return the localhost. 5 String getHostName() This method is used to get the name of the IP address. 6 String getHostAddress() This method returns the IP address in the form of a string in a textual display. 7 String toString() This method is used to convert the IP address to a string.
URL
• The Java URL class represents an URL. URL is an acronym
for Uniform Resource Locator. It points to a resource on the
World Wide Web.
• URL contains many information:
• Protocol: In this case, http is the protocol.
• Server name or IP Address: In this case,
www.javatpoint.com is the server name.
• Port Number: It is an optional attribute. If we write http//ww.
javatpoint.com:80/sonoojaiswal/ , 80 is the port number. If
port number is not mentioned in the URL, it returns - 1.
• File Name or directory name: In this case, index.jsp is the
file name.
Constructors
• URL(String spec)
• Creates an instance of a URL from the
String representation.
• URL(String protocol, String host, int port, String file)
• Creates an instance of a URL from the
given protocol, host, port number, and file.
• URL(String protocol, String host, String file)
• Creates an instance of a URL from the
given protocol name, host name, and file
name.
Methods
• public String getProtocol() it returns the protocol of the
URL.
• public String getHost() it returns the host name of the
URL.
• public String getPort() it returns the Port Number of the
URL.
• public String getFile() it returns the file name of the URL.
• public String getAuthority() it returns the authority of
the URL.
• public String toString() it returns the string
representation of the URL.
• public String getQuery() it returns the query string of the
URL.
• public String getDefaultPort() it returns the default port
of the URL.