SlideShare a Scribd company logo
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

More Related Content

Similar to 03-JDBC.pptx

Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical file
varun arora
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
Maher Abdo
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
Vikas Jagtap
 
Final Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.pptFinal Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.ppt
TabassumMaktum
 
Jdbc complete
Jdbc completeJdbc complete
Jdbc complete
Sandeep Rawat
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
Rakesh Kumar Ray
 
Airline report
Airline reportAirline report
Airline report
SimranBani
 
Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)
Som Prakash Rai
 
Spring jdbc dao
Spring jdbc daoSpring jdbc dao
Spring jdbc dao
Anuj Singh Rajput
 
Jdbc
JdbcJdbc
java 4 Part 1 computer science.pptx
java 4 Part 1 computer science.pptxjava 4 Part 1 computer science.pptx
java 4 Part 1 computer science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
10 J D B C
10  J D B C10  J D B C
10 J D B C
guest04b824
 
Jdbc new
Jdbc newJdbc new
Jdbc new
sumit kushwah
 
jdbc
jdbcjdbc
jdbc
shreeuva
 
JDBC
JDBCJDBC
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
Arumugam90
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
Arumugam90
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
Dhyey Dattani
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
Dhyey Dattani
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
Sourabrata Mukherjee
 

Similar to 03-JDBC.pptx (20)

Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical file
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Final Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.pptFinal Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.ppt
 
Jdbc complete
Jdbc completeJdbc complete
Jdbc complete
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
Airline report
Airline reportAirline report
Airline report
 
Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)Jdbc Complete Notes by Java Training Center (Som Sir)
Jdbc Complete Notes by Java Training Center (Som Sir)
 
Spring jdbc dao
Spring jdbc daoSpring jdbc dao
Spring jdbc dao
 
Jdbc
JdbcJdbc
Jdbc
 
java 4 Part 1 computer science.pptx
java 4 Part 1 computer science.pptxjava 4 Part 1 computer science.pptx
java 4 Part 1 computer science.pptx
 
10 J D B C
10  J D B C10  J D B C
10 J D B C
 
Jdbc new
Jdbc newJdbc new
Jdbc new
 
jdbc
jdbcjdbc
jdbc
 
JDBC
JDBCJDBC
JDBC
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
 

Recently uploaded

Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
Wouter Lemaire
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
IndexBug
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
Zilliz
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
David Brossard
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
Uni Systems S.M.S.A.
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
Zilliz
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
Matthew Sinclair
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
Zilliz
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
panagenda
 
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdfAI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
Techgropse Pvt.Ltd.
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
Matthew Sinclair
 
Things to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUUThings to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUU
FODUU
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
Zilliz
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
Quotidiano Piemontese
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
Tomaz Bratanic
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
Matthew Sinclair
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
SitimaJohn
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
kumardaparthi1024
 

Recently uploaded (20)

Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
UI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentationUI5 Controls simplified - UI5con2024 presentation
UI5 Controls simplified - UI5con2024 presentation
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceAI 101: An Introduction to the Basics and Impact of Artificial Intelligence
AI 101: An Introduction to the Basics and Impact of Artificial Intelligence
 
Infrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI modelsInfrastructure Challenges in Scaling RAG with Custom AI models
Infrastructure Challenges in Scaling RAG with Custom AI models
 
OpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - AuthorizationOpenID AuthZEN Interop Read Out - Authorization
OpenID AuthZEN Interop Read Out - Authorization
 
Microsoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdfMicrosoft - Power Platform_G.Aspiotis.pdf
Microsoft - Power Platform_G.Aspiotis.pdf
 
Full-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalizationFull-RAG: A modern architecture for hyper-personalization
Full-RAG: A modern architecture for hyper-personalization
 
20240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 202420240609 QFM020 Irresponsible AI Reading List May 2024
20240609 QFM020 Irresponsible AI Reading List May 2024
 
Programming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup SlidesProgramming Foundation Models with DSPy - Meetup Slides
Programming Foundation Models with DSPy - Meetup Slides
 
HCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAUHCL Notes and Domino License Cost Reduction in the World of DLAU
HCL Notes and Domino License Cost Reduction in the World of DLAU
 
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdfAI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
AI-Powered Food Delivery Transforming App Development in Saudi Arabia.pdf
 
20240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 202420240605 QFM017 Machine Intelligence Reading List May 2024
20240605 QFM017 Machine Intelligence Reading List May 2024
 
Things to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUUThings to Consider When Choosing a Website Developer for your Website | FODUU
Things to Consider When Choosing a Website Developer for your Website | FODUU
 
Building Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and MilvusBuilding Production Ready Search Pipelines with Spark and Milvus
Building Production Ready Search Pipelines with Spark and Milvus
 
National Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practicesNational Security Agency - NSA mobile device best practices
National Security Agency - NSA mobile device best practices
 
GraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracyGraphRAG for Life Science to increase LLM accuracy
GraphRAG for Life Science to increase LLM accuracy
 
20240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 202420240607 QFM018 Elixir Reading List May 2024
20240607 QFM018 Elixir Reading List May 2024
 
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptxOcean lotus Threat actors project by John Sitima 2024 (1).pptx
Ocean lotus Threat actors project by John Sitima 2024 (1).pptx
 
GenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizationsGenAI Pilot Implementation in the organizations
GenAI Pilot Implementation in the organizations
 

03-JDBC.pptx

  • 1. CHAPTER Three JDBC (Java Database Connectivity) 8/22/2023 1
  • 2. 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
  • 4. 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
  • 5. 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
  • 6. 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
  • 7. 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
  • 8. 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
  • 9. 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");
  • 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 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
  • 12. 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
  • 13. 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…
  • 14. 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…
  • 15. 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…