CHAPTER Three
JDBC
(Java Database Connectivity)
8/22/2023 1
JDBC Overview
ļ‚— JDBC is an Application Programming Interface (API) that allows a
Java application to access any kind of tabular data, such as a
database.
ļ‚— JDBC allows us to develop Java applications that can:
ļ‚§ Connect to a data source, such as a database
ļ‚§ Send queries and update statements to the database
ļ‚§ Retrieve and process the results received from the database
ļ‚— JDBC enables us to develop data-centric applications that can
access and manipulate data from diverse range of databases.
ļ‚— For this, JDBC API consists of different types of JDBC drivers,
8/22/2023 2
8/22/2023 3
What is JDBC Driver?
ļ‚— A JDBC driver is a software component enabling a Java
application to interact with a database server.
ļ‚— For example, using JDBC drivers enable you to open
database connections and to interact with it by sending
SQL or database commands then receiving results with
Java.
ļ‚— There are four types of JDBC drivers to connect with different
types of databases. These are:
ļ‚– Type 1: JDBC-ODBC Bridge Driver
ļ‚– Type 2: JDBC-Native API Driver
ļ‚– Type 3: JDBC-Network-Protocol Driver (middleware driver)
8/22/2023 4
Some Popular JDBC Drivers and URL format
8/22/2023 5
RDBMS JDBC Driver Name and DB URL format
MYSQL
Driver Name
com.mysql.jdbc.Driver
Database URL format:
jdbc:mysql//hostname/databaseName
Oracle
Driver Name:
oracle.jdbc.driver.OracleDriver
Database URL format:
jdbc:oracle:thin@hostname:portnumber:databaseName
JavaDB
Driver Name:
org.apache.derby.jdbc.ClientDriver
Database URL format:
jdbc:derby://localhost:1527/databaseName
Access
Driver Name:
sun.jdbc.odbc.JdbcOdbcDriver
Database URL format:
jdbc:odbc:databaseName
Steps to Connect Database Using JDBC
To perform deferent operation on data in the database by using JDBC,
it is required to follow the following steps in application
1. Import package
2. Load the JDBC driver
3. Establish the Connection
4. Create a Statement object
5. Execute a query
6. Process the results
7. Close the connection
8/22/2023 6
Core Components of JOBC
ļ‚— The core components of JOBC are provided under the java . Sql
package.
ļ‚— These core components includes, but are not limited to:
ļ‚— JDBC Drivers: Allow establishing a communication between a
database and a Java application. It is available as Driver interface in
the java. sql package.
ļ‚— Connections: Allow establishing a connection session with the
database. It is available as the Connection interface in the java. sql
package.
ļ‚— Statements: Allow executing static SQL statements and returning
the results. It is available as the Statement interface in the java .sql
package.
ļ‚— To execute dynamic SQL statements the PreparedStatement
8/22/2023 7
Core Components of JOBC…
ļ‚— Result Sets: Allow storing the data retrieved as a result of a SQL
queries in a tabular format. It is available as the Statement
interface in the java.sql package.
ļ‚— Database Meta Data : Allow to get information about the
database as a whole. It is available as DatabaseMetaData
interface in java sql package.
ļ‚— Result Set Meta Data: Allows to get information about the types
and properties of the columns in the ResultSet object. It is
available as the ResultSetMetaData interface in the java sql
package.
8/22/2023 8
Connection Establishment Example….
8/22/2023 9
Connection connection = DriverManager.getConnection(databaseURL);
Database: URL Pattern
Access : jdbc:odbc:dataSource
MySQL: jdbc:mysql://hostname:port/dbname, username, password
Oracle: jdbc:oracle:thin:@hostname:port#:oracleDBSID, username, pwd
Examples:
For Access:
Connection connection = DriverManager.getConnection
("jdbc:odbc:ExampleMDBDataSource");
For MySQL:
Connection connection =
DriverManager.getConnectio("jdbc:mysql://localhost/test,username,password");
For Oracle:
Connection connection = DriverManager.getConnection
("jdbc:oracle:thin:@liang.armstrong.edu:1521:orcl", "scott", "tiger");
Execute a query
ļ‚— boolean execute (String sql)
ļ‚§ Executes the given SQL statement, which may return multiple results.
Is used in the situations where you are not sure whether the query to
be executed is an insert, update, or delete statement or it is a query to
retrieve data
ļ‚— ResultSet executeQuery(String sql)
ļ‚— Executes the given SQL statement, which returns a single ResultSet
object
ļ‚— Is used to execute the queries that retrieve data from the databse.
ļ‚— int executeUpdate(String sql)
ļ‚— Executes the given SQL statements which may be CREATE, INSERT,
UPDATE, or DELETE statement or an SQL statement that returns
nothing, such as an SQL DDL statement.
8/22/2023 10
Example of JDBC using MYSQL Database
ļ‚— Perform CRUD Operation includes
ļ‚–Create/Insert Records
ļ‚–Read/View Record
ļ‚–Update Record
ļ‚–Delete Record
ļ‚— All the above operations including Database and Result Set
Meta Data are preformed in the following example.
8/22/2023 11
8/22/2023 12
//import JDBC packages
package JDBDemo;
import java.sql.*;
import java.sql.PreparedStatement;
public class CRUD {
public static void main(String[] args) throws ClassNotFoundException {
// JDBC and database properties
String driver="com.mysql.cj.jdbc.Driver";
String dburl="jdbc:mysql://localhost:3306/jdbc";
String username="root";
String password="";
try {
//load driver and create connection
Class.forName(driver);
Connection con=DriverManager.getConnection(dburl,username,password);
System.out.println("Successfully connected");
//Create Table
String sqlct="create table student(sid int(11), name varchar(20))";
PreparedStatement prstmtct=con.prepareStatement(sqlct);
prstmtct.executeUpdate();
System.out.println("Successfully Created");
Perform CRUD Operation
8/22/2023 13
//Insert data
String sqlin="insert into student values(?,?)";
PreparedStatement prstmtin=con.prepareStatement(sqlin);
prstmtin.setInt(1, 1);
prstmtin.setString(2, "chala");
prstmtin.executeUpdate();
//update specific recorded
String sqlup="update student set name=? where sid=?";
PreparedStatement prstmtud=con.prepareStatement(sqlup);
prstmtud.setString(1,"Abebe");
prstmtud.setInt(2, 1);
prstmtud.executeUpdate();
System.out.println("Successfully Updated");
//delete specific recorded
String sqldel="delete from student where sid=?";
PreparedStatement prstmtdel=con.prepareStatement(sqldel);
prstmtdel.setInt(1, 3);
prstmtdel.executeUpdate();
System.out.println("Successfully Deleted ");
Perform CRUD Operation…
8/22/2023 14
//selecte/view data
String vd="select * from Student";
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(vd);
System.out.println("Sid t Name");
while(rs.next()){
int sid=rs.getInt(1);
String name= rs.getString(2);
System.out.println(sid+"t"+name);
}
//Database metadata
DatabaseMetaData dbmd=con.getMetaData();
System.out.println("Driver "+ dbmd.getDriverName());
System.out.println("driver version "+dbmd.getDriverVersion());
System.out.println("database product
name"+dbmd.getDatabaseProductName());
System.out.println("database version
"+dbmd.getDatabaseProductVersion());
System.out.println("user name "+dbmd.getUserName());
Perform CRUD Operation…
8/22/2023 15
//Result set metadata
ResultSetMetaData rsmd=rs.getMetaData();
System.out.println("number of columan "+rsmd.getColumnCount());
System.out.println("name of the column "+ rsmd.getColumnName(1));
System.out.println("column type "+rsmd.getColumnTypeName(2));
System.out.println("columan type size "+rsmd.getColumnDisplaySize(1));
System.out.println("table name "+rsmd.getTableName(1));
//Close connections
stmt.close();
con.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
Perform CRUD Operation…
8/22/2023 16

03-JDBC.pptx

  • 1.
    CHAPTER Three JDBC (Java DatabaseConnectivity) 8/22/2023 1
  • 2.
    JDBC Overview ļ‚— JDBCis an Application Programming Interface (API) that allows a Java application to access any kind of tabular data, such as a database. ļ‚— JDBC allows us to develop Java applications that can: ļ‚§ Connect to a data source, such as a database ļ‚§ Send queries and update statements to the database ļ‚§ Retrieve and process the results received from the database ļ‚— JDBC enables us to develop data-centric applications that can access and manipulate data from diverse range of databases. ļ‚— For this, JDBC API consists of different types of JDBC drivers, 8/22/2023 2
  • 3.
  • 4.
    What is JDBCDriver? ļ‚— A JDBC driver is a software component enabling a Java application to interact with a database server. ļ‚— For example, using JDBC drivers enable you to open database connections and to interact with it by sending SQL or database commands then receiving results with Java. ļ‚— There are four types of JDBC drivers to connect with different types of databases. These are: ļ‚– Type 1: JDBC-ODBC Bridge Driver ļ‚– Type 2: JDBC-Native API Driver ļ‚– Type 3: JDBC-Network-Protocol Driver (middleware driver) 8/22/2023 4
  • 5.
    Some Popular JDBCDrivers and URL format 8/22/2023 5 RDBMS JDBC Driver Name and DB URL format MYSQL Driver Name com.mysql.jdbc.Driver Database URL format: jdbc:mysql//hostname/databaseName Oracle Driver Name: oracle.jdbc.driver.OracleDriver Database URL format: jdbc:oracle:thin@hostname:portnumber:databaseName JavaDB Driver Name: org.apache.derby.jdbc.ClientDriver Database URL format: jdbc:derby://localhost:1527/databaseName Access Driver Name: sun.jdbc.odbc.JdbcOdbcDriver Database URL format: jdbc:odbc:databaseName
  • 6.
    Steps to ConnectDatabase Using JDBC To perform deferent operation on data in the database by using JDBC, it is required to follow the following steps in application 1. Import package 2. Load the JDBC driver 3. Establish the Connection 4. Create a Statement object 5. Execute a query 6. Process the results 7. Close the connection 8/22/2023 6
  • 7.
    Core Components ofJOBC ļ‚— The core components of JOBC are provided under the java . Sql package. ļ‚— These core components includes, but are not limited to: ļ‚— JDBC Drivers: Allow establishing a communication between a database and a Java application. It is available as Driver interface in the java. sql package. ļ‚— Connections: Allow establishing a connection session with the database. It is available as the Connection interface in the java. sql package. ļ‚— Statements: Allow executing static SQL statements and returning the results. It is available as the Statement interface in the java .sql package. ļ‚— To execute dynamic SQL statements the PreparedStatement 8/22/2023 7
  • 8.
    Core Components ofJOBC… ļ‚— Result Sets: Allow storing the data retrieved as a result of a SQL queries in a tabular format. It is available as the Statement interface in the java.sql package. ļ‚— Database Meta Data : Allow to get information about the database as a whole. It is available as DatabaseMetaData interface in java sql package. ļ‚— Result Set Meta Data: Allows to get information about the types and properties of the columns in the ResultSet object. It is available as the ResultSetMetaData interface in the java sql package. 8/22/2023 8
  • 9.
    Connection Establishment Example…. 8/22/20239 Connection connection = DriverManager.getConnection(databaseURL); Database: URL Pattern Access : jdbc:odbc:dataSource MySQL: jdbc:mysql://hostname:port/dbname, username, password Oracle: jdbc:oracle:thin:@hostname:port#:oracleDBSID, username, pwd Examples: For Access: Connection connection = DriverManager.getConnection ("jdbc:odbc:ExampleMDBDataSource"); For MySQL: Connection connection = DriverManager.getConnectio("jdbc:mysql://localhost/test,username,password"); For Oracle: Connection connection = DriverManager.getConnection ("jdbc:oracle:thin:@liang.armstrong.edu:1521:orcl", "scott", "tiger");
  • 10.
    Execute a query ļ‚—boolean execute (String sql) ļ‚§ Executes the given SQL statement, which may return multiple results. Is used in the situations where you are not sure whether the query to be executed is an insert, update, or delete statement or it is a query to retrieve data ļ‚— ResultSet executeQuery(String sql) ļ‚— Executes the given SQL statement, which returns a single ResultSet object ļ‚— Is used to execute the queries that retrieve data from the databse. ļ‚— int executeUpdate(String sql) ļ‚— Executes the given SQL statements which may be CREATE, INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement. 8/22/2023 10
  • 11.
    Example of JDBCusing MYSQL Database ļ‚— Perform CRUD Operation includes ļ‚–Create/Insert Records ļ‚–Read/View Record ļ‚–Update Record ļ‚–Delete Record ļ‚— All the above operations including Database and Result Set Meta Data are preformed in the following example. 8/22/2023 11
  • 12.
    8/22/2023 12 //import JDBCpackages package JDBDemo; import java.sql.*; import java.sql.PreparedStatement; public class CRUD { public static void main(String[] args) throws ClassNotFoundException { // JDBC and database properties String driver="com.mysql.cj.jdbc.Driver"; String dburl="jdbc:mysql://localhost:3306/jdbc"; String username="root"; String password=""; try { //load driver and create connection Class.forName(driver); Connection con=DriverManager.getConnection(dburl,username,password); System.out.println("Successfully connected"); //Create Table String sqlct="create table student(sid int(11), name varchar(20))"; PreparedStatement prstmtct=con.prepareStatement(sqlct); prstmtct.executeUpdate(); System.out.println("Successfully Created"); Perform CRUD Operation
  • 13.
    8/22/2023 13 //Insert data Stringsqlin="insert into student values(?,?)"; PreparedStatement prstmtin=con.prepareStatement(sqlin); prstmtin.setInt(1, 1); prstmtin.setString(2, "chala"); prstmtin.executeUpdate(); //update specific recorded String sqlup="update student set name=? where sid=?"; PreparedStatement prstmtud=con.prepareStatement(sqlup); prstmtud.setString(1,"Abebe"); prstmtud.setInt(2, 1); prstmtud.executeUpdate(); System.out.println("Successfully Updated"); //delete specific recorded String sqldel="delete from student where sid=?"; PreparedStatement prstmtdel=con.prepareStatement(sqldel); prstmtdel.setInt(1, 3); prstmtdel.executeUpdate(); System.out.println("Successfully Deleted "); Perform CRUD Operation…
  • 14.
    8/22/2023 14 //selecte/view data Stringvd="select * from Student"; Statement stmt=con.createStatement(); ResultSet rs=stmt.executeQuery(vd); System.out.println("Sid t Name"); while(rs.next()){ int sid=rs.getInt(1); String name= rs.getString(2); System.out.println(sid+"t"+name); } //Database metadata DatabaseMetaData dbmd=con.getMetaData(); System.out.println("Driver "+ dbmd.getDriverName()); System.out.println("driver version "+dbmd.getDriverVersion()); System.out.println("database product name"+dbmd.getDatabaseProductName()); System.out.println("database version "+dbmd.getDatabaseProductVersion()); System.out.println("user name "+dbmd.getUserName()); Perform CRUD Operation…
  • 15.
    8/22/2023 15 //Result setmetadata ResultSetMetaData rsmd=rs.getMetaData(); System.out.println("number of columan "+rsmd.getColumnCount()); System.out.println("name of the column "+ rsmd.getColumnName(1)); System.out.println("column type "+rsmd.getColumnTypeName(2)); System.out.println("columan type size "+rsmd.getColumnDisplaySize(1)); System.out.println("table name "+rsmd.getTableName(1)); //Close connections stmt.close(); con.close(); } catch (Exception e) { System.out.println(e); } } } Perform CRUD Operation…
  • 16.