Enterprise Programming (303105309)
Prof. Pirmohammad, Assistant Professor
Computer Science & Engineering
JDBC And Architecture of JDBC
Introduction to JDBC (Java Database Connectivity)
Why Should We Use JDBC
Components of JDBC
Different Types of Architecture of JDBC
The architecture of the JDBC consists of two and three tiers model in order to access the given database.
Two-tier model: A java application communicates directly to the data source. The JDBC driver enables the communication between the application and the data source. When a user sends a query to the data source, the answers for those queries are sent back to the user in the form of results. The data source can be located on a different machine on a network to which a user is connected. This is known as a client/server configuration, where the user’s machine acts as a client, and the machine has the data source running acts as the server.
Different Types of Architecture of JDBC
Three-tier model: In this, the user’s queries are sent to middle-tier services, from which the commands are again sent to the data source. The results are sent back to the middle tier, and from there to the user.
This type of model is found very useful by management information system directors.
JDBC Drivers
JDBC Drivers
JDBC Drivers
Type-1 driver or JOBC-ODBC bridge driver
JDBC Drivers
Advantages:
Disadvantages:
JDBC Drivers
Type-2 driver or Native-API driver
JDBC Drivers
Advantages:
Disadvantages:
JDBC Drivers
Type-3 driver or Network Protocol driver
JDBC Drivers
Type-4 driver or Thin driver
JDBC Drivers
Advantages:
Which Driver to Use When?
Interfaces of JDBC API Classes of JDBC API
Class forName() method
Syntax
Public static Class<T> forName(String className) throws
ClassNotFoundException
Example
class.forName(“com.mysql.cj.jdbc.Driver”) -> For MySql Connectivity
class.forName(“oracle.jdbc.driver.OracleDriver”) -> For Oracle connectivity
Driver Manager
Methods:
public static void registerDriver(Driver driver)
public static void deregisterDriver(Driver driver)
public static Connection getConnection(String Url)
public static Connection getConnection(String Url, String username, String password)
Example
String connectionUrl = “jdbc:mysql://localhost:3307/dbname”
Connection conn = DriverManager.getConnection(connectionUrl, "root", "password");
Connection Interface
Methods
public Statement createStatement()
public Statement createStatement(int resultSetType,int resultSetConcurrency)
public void setAutoCommit(boolean status)
public void commit()
public void rollback()
public void close()
Statement Interface
The Statement interface is used for executing queries using the database. This interface is a factory of ResultSet.
It is used to get the Object of ResultSet.
Methods
public ResultSet executeQuery(String sql)
public int executeUpdate(String sql)
public boolean execute(String sql)
public int[] executeBatch()
Example
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(“Select * From students”);
ResultSet Interface
Statement stmt = con.createStatement(ResultSet. TYPE _SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
Example
ResultSet result = stmt.executeQuery(“Select * From students”);
Example
try {
Class. forName("com.mysql.cj.jdbc.Driver") ;
conn =DriverManager.getConnection("jdbc:mysql://localhost:3306/myData","root", "pwd" ) ;
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery(“select * from employees”);
while(result.next()) {
System.out.println(result.getInt(1) + "\t" + result.getString(2) +" "+ result.getString(3));
}
conn.close();
}
catch (Exception e) {
System.out.println("my Error :" + e.getMessage());
}
PreparedStatement Interface
Example
PreparedStatement stmt = conn.prepareStatement(“insert into Employees values(?,?, ?)”);
stmt.setint(1, 1001)
stmt.setString(2, “Mahesh”)
stmt.setint(3, “Shah”)
int result = stmt.executeUpdate();
ResultSetMetaData Interface
ResultSetMetaData interface is used to get metadata from the ResultSet object.
Metadata are the data about data.
Methods
public int getColumnCount() throws SQLException
public String getColumnName(int index) throws SQLException
public String getColumnTypeName(int index) throws SQLException
public String getTableName(int index) throws SQLException
Example
ResultSetMetaData resmd = result.getMetaData();
System.out.printIn("Total columns: “ + resmd.getColumnCount());
System.out.printIn("Column Name of 1st column: “ + resmd.getColumnName(1));
System.out.printIn("Column Type Name of ist column: “ +resmd.getColumnTypeName(1));
DatabaseMetaData Interface
Example
DatabaseMetaData dbmd=con.getMetaData();
System.out.printiIn("Driver Name: "+dbmd.getDriverName());
System.out.printIn("Driver Version: "+dbmd.getDriverVersion());
System.out.printiIn("“UserName: "+dbmd.getUserName());
System.out.printIn("Database Product Name: "+dbmd.get DatabaseProduct Name());
System.out.printIn("Database Product Version: "+dbmd.getDatabase Product Version());
RowSet Interface
1. JdbcRowSet
2. CachedRowSet
3. WebRowSet
4. JoinRowSet
5. FilteredRowSet
JdbcRowSet
CachedRowSet
WebRowSet
FilteredRowSet
Image source : Google
Join RowSet Interface
Jdbc with Oracle
Java Database Connectivity with 5 Steps
There are 5 steps to connect any java application with the database using JDBC. These steps are as follows:
1) Register the driver class
The forName() method of Class class is used to register the driver class. This method is used to dynamically load the driver class. Syntax of forName() method public static void forName(String className)throws ClassNotFoundException Example to register the OracleDriver class Here, Java program is loading oracle driver to esteblish database connection. Class.forName("oracle.jdbc.driver.OracleDriver");
|
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 Oracle database Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","password"); |
3) Create the Statement object
The createStatement() method of Connection interface is used to create 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 connection object statement and ResultSet will be closed automatically. The close() method of Connection interface is used to close the connection. Syntax of close() method public void close()throws SQLException Example to close connection con.close(); |
JDBC with Oracle and Mysql
Java Database Connectivity with Oracle
To connect java application with the oracle database, we need to follow 5 following steps. In this example, we are using Oracle 10g as the database. So we need to know following information for the oracle database:
Java Database Connectivity with Oracle
Create a Table
Before establishing connection, let's first create a table in oracle database. Following is the SQL query to create a table.
create table emp(id number(10),name varchar2(40),age number(3));
Example to Connect Java Application with Oracle database
In this example, we are connecting to an Oracle database and getting data from emp table. Here, system and oracle are the username and password of the Oracle database.
Example to Connect Java Application with Oracle database
import java.sql.*;
class OracleCon{
public static void main(String args[]){
try{
//step1 load the driver class
Class.forName("oracle.jdbc.driver.OracleDriver");
//step2 create the connection object
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
//step3 create the statement object
Statement stmt=con.createStatement();
//step4 execute query
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
//step5 close the connection object
con.close();
}
catch(Exception e){ System.out.println(e);}
}
}
Example to Connect Java Application with MySQL database
Example to Connect Java Application with MySQL database
import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName(“com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
“jdbc:mysql://localhost:3306/sonoo”,”root“,”root”);
//here sonoo is databse name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}
catch(Exception e){ System.out.println(e);
}
}
}
Maven Integration with Eclipse
What is Maven?
Definition: Maven is a build automation and project management tool for Java projects.
It simplifies the process of building, testing, and deploying Java applications by managing project dependencies and providing a standardized project structure.
Purpose: Manages project dependencies, enforces a standard project structure, and automates the build process (compile, test, package).
Maven's Objectives
Benefits of Using Maven:
Automatic Dependency Management:
Standardized Project Structure:
Build Automation:
Integration with IDEs:
Benefits of Using Maven:
Plugin Ecosystem:
Improved Collaboration:
How to Integrate Maven with Eclipse:
Install Maven in Eclipse:
Create a Maven Project:
Add Dependencies:
Build and Run the Project:
Key Terms:
POM.xml
What is POM file?
Default repo is maven repository.
Default execution goal is ‘jar’.
Default source code location is src/main/java.
Default test code location is src/test/java.
Example
<?xml version="1.0" encoding="UTF-8" standalone="no" ?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmins:xsi="ht
tp://www.w3.org/2001/XMLSchema-instance"xSi:schemaLocation="http://maven.apache.org/POM/4.0.0http: //maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<packaging>pom</packaging>
<parent>
<grouplid>org.springframework.boot</groupId>
<artifactid>spring-boot-starter-parent</artifactId>
<version>2.2.0.M5</version>
</parent>
</project>