SlideShare una empresa de Scribd logo
1 de 34
JAVA
JDBC
Prepared by
Miss. Arati A. Gadgil
JDBC
Java JDBC is a java API to connect and execute query with the
database. JDBC API uses jdbc drivers to connect with the database.
API
API (Application programming interface) is a document that
contains description of all the features of a product or software. It
represents classes and interfaces that software programs can follow
to communicate with each other. An API can be created for
applications, libraries, operating systems, etc
JDBCDriver
JDBC Driver is a software component that enables java application to
interact with the database. There are 4 types of JDBC drivers
1.JDBC-ODBC bridge driver
2.Native-API driver (partially java driver)
3.Network Protocol driver (fully java driver)
4.Thin driver (fully java driver)
JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the
database. The JDBC-ODBC bridge driver converts JDBC method calls
into the ODBC function calls.
connect to the database
Steps
1. Register the driver class
2. Creating connection
3. Creating statement
4. Executing queries
5. Closing connection
1) Register the driver class
public static void forName(String className)throws
ClassNotFoundException
Example
Class.forName("oracle.jdbc.driver.OracleDriver");
2)Create the connection object
1) public static Connection getConnection(String url)throws
SQLException
2) public static Connection getConnection(String url,String name,String
password) throws SQLException
Example
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.
public Statement createStatement()throws SQLException
Example
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.
public ResultSet executeQuery(String sql)throws SQLException
Example
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.
public void close()throws SQLException
Example
con.close();
DatabaseMetaData Interface
DatabaseMetaData interface provides methods to get meta data of a
database such as database product name, database product version,
driver name, name of total number of tables, name of total number of
views etc.
Methods
public String getDriverName()throws SQLException
it returns the name of the JDBC driver.
public String getDriverVersion()throws SQLException
it returns the version number of the JDBC driver.
public String getUserName()throws SQLException
it returns the username of the database.
public String getDatabaseProductName()throws SQLException
it returns the product name of the database.
public String getDatabaseProductVersion()throws SQLException
it returns the product version of the database.
public ResultSet getTables(String catalog, String schemaPattern,
String tableNamePattern, String[] types)throws SQLException
it returns the description of the tables of the specified catalog. The
table type can be TABLE, VIEW, ALIAS, SYSTEM TABLE,
SYNONYM etc.
Transaction
Transaction represents a single unit of work
Properties
Atomicity means either all successful or none.
Consistency ensures bringing the database from one consistent state to
another consistent state.
Isolation ensures that transaction is isolated from other transaction.
Durability means once a transaction has been committed, it will remain
so, even in the event of errors, power loss etc.
 Connectioninterface
In JDBC, Connection interface provides methods to manage
transaction.
Methods
void setAutoCommit(boolean status)
It is true bydefault means each transaction is committed by
default.
void commit()
commits the transaction.
void rollback()
cancels the transaction.
What is JDBC?
JDBC stands for Java Database Connectivity, which is a standard Java
API for database-independent connectivity between the Java prog
ramming language and a wide range of databases.
Common JDBC Components
DriverManager: This class manages a list of database drivers.
Driver: This interface handles the communications with the database
server.
Connec tion: This interface with all methods for contacting a database.
Statement: You use objects created from this interface to submit the
SQL statements to the database.
ResultSet: These objects hold data retrieved from a database after you
execute an SQL query using Statement objects. It acts as an iterator to
allow you to move throug h its data.
SQLException: T his class handles any errors that occur in a database
application.
JDBC-SQLSYNTAX
Structured Query Language (SQL) is a standardized language that allows
you to perform operations on a database, such as creating entries, reading
content, updating content, and deleting entries.
Create Database:
The CREAT E DATABASE statement is used for creating a new
database. The syntax is:
SQL> CREATE DATABASE DATABASE_NAME;
Example
The following SQL statement creates a Database named EMP:
SQL> CREATE DATABASE EMP;
Drop Database:
The DROP DATABASE statement is used for deleting an existing
database. The syntax is:
SQL> DROP DATABASE DATABASE_NAME;
Create Table:
The CREAT E TABLE statement is used for creating a new table. The
syntax is:
SQL> CREATE TABLE table_name
(
column_name column_data_type,
...
);
Example:
The following SQL statement creates a table named Employees with four
columns:
SQL> CREATE TABLE Employees
( id INT NOT NULL,
age INT NOT NULL,
first VARCHAR(255),
last VARCHAR(255),
PRIMARY KEY ( id )
);
INSERT Data:
The syntax for INSERT looks similar to the following , where column1,
column2, and so on represent the new data to appear in the respective
columns:
SQL> INSERT INTO table_name VALUES (column1, column2, ...);
Example:
The following SQL INSERT statement inserts a new row in the
Employees database created earlier:
SQL> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
SELECT Data:
The SELECT statement is used to retrieve data from a database. The
syntax for SELECT is:
SQL> SELECT column_name, column_name, ...
FROM table_name
WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <,
>, <=,and >=, as well as the BETWEEN
and LIKE operators.
Example
The following SQL statement selects the ag e, first and last columns
from the Employees table where id column is
100:
SQL> SELECT first, last, age
FROM Employees
WHERE id = 100;
The following SQL statement selects the age, first and last columns from
the Employees table where first column contains Zara
SQL> SELECT first, last, age
FROM Employees
WHERE first LIKE '%Zara%';
The following SQL statement selects the age, first and last columns from
the Employees table where first column contains “a” at end
SQL> SELECT first, last, age
FROM Employees
WHERE first LIKE '%a';
The following SQL statement selects the age, first and last columns from
the Employees table where first column contains a at start
SQL> SELECT first, last, age
FROM Employees
WHERE first LIKE 'a%';
UPDATE Data:
The UPDAT E statement is used to update data. The syntax for
UPDATE is:
SQL> UPDATE table_name
SET column_name = value, column_name = value, ...
WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <,
>, <=,and >=, as well as the BETWEEN
and LIKE operators.
Example:
T he following SQL UPDAT E statement changes the age column of the
employee whose id is 100:
SQL> UPDATE Employees SET age=20 WHERE id=100;
DELETE Data:
The DELETE statement is used to delete data from tables. The syntax for
DELETE is:
SQL> DELETE FROM table_name WHERE conditions;
The WHERE clause can use the comparison operators such as =, !=, <,
>, <=,and >=, as well as the BETWEEN
and LIKE operators.
Example:
T he following SQL DELET E statement delete the record of the
employee whose id is 100:
SQL> DELETE FROM Employees WHERE id=100;
ImportJDBCPackages
import java.sql.* ; // for standard JDBC programs
import java.math.* ; // for BigDecimal and BigInteger support
Register JDBC Driver
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
}
catch(ClassNotFoundException ex)
{
System.out.println("Error: unable to load driver class!");
System.exit(1);
}
Create Connection Object:
Using a database URL with a username and password:
String URL = "jdbc:oracle:thin:@amrood:1521:EMP";
String USER = "username";
String PASS = "password"
Connection conn = DriverManager.getConnection(URL, USER, PASS);
Closing JDBC connections:
conn.close();
Statement
Use for general-purpose access to your database. Useful when you are
using static SQL statements at runtime. T he Statement interface cannot
accept parameters.
PreparedStatement :
Use when you plan to use the SQL statements many times. The
PreparedStatement interface accepts input parameters at runtime.
CallableStatement :
Use when you want to access database stored procedures. The
CallableStatement interface can also accept runtime input parameters.
Creating Statement Object
Before you can use a Statement object to execute a SQL statement, you
need to create one using the Connection
object's createStatement( ) method, as in the following example:
Statement stmt = null;
try
{
stmt = conn.createStatement( );
. . .
} catch (SQLException e)
{
. . .
}
finally {
. . .
}
Once you've created a Statement object, you can then use it to execute a
SQL statement with one of its three execute methods.
boolean execute(String SQL) : Returns a boolean value of true if a
ResultSet object can be retrieved; otherwise, it returns false. Use this
method to execute SQL DDL statements or when you need to use truly
dynamic SQL.
int executeUpdate(String SQL) : Returns the numbers of rows affected
by the execution of the SQL statement. Use this method to execute SQL
statements for which you expect to get a number of rows affected - for
example, an INSERT , UPDAT E, or DELET E statement.
ResultSet executeQuery(String SQL) : Returns a ResultSet object. Use
this method when you expect to get a result set, as you would with a
SELECT statement.
31
Rowsets
Rowsets are the central objects that enable OLE DB components to
expose and manipulate data in tabular form. A rowset object is a set of
rows in which each row has columns of data.
Query processors present query results in the form of rowsets.
32
ResultSet
The SQL statements that read data from a database query, return the data
in a result set. The SELECT statement is the standard way to select rows
from a database and view them in a result set.
The java.sql.ResultSet interface represents the result set of a database
query.
A ResultSet object maintains a cursor that points to the current row in
the result set. The term "result set" refers to the row and column data
contained in a ResultSet object.
The ResultSet interface contains many methods for getting the data of
the current row.
33
public int getInt(String columnName) throws SQLException
Returns the int in the current row in the column named
columnName
public int getInt(int columnIndex) throws SQLException
Returns the int in the current row in the specified column index.
The column index starts at 1, meaning the first column of a row is
1, the second column of a row is 2, and so on.
Similarly, there are get methods in the ResultSet interface for each of the
eight Java primitive types, as well as common types such as
java.lang.String, java.lang.Object, and java.net.URL
Thank You
34

Más contenido relacionado

La actualidad más candente

1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)Fad Zulkifli
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQLAdil Mehmoood
 
Database connect
Database connectDatabase connect
Database connectYoga Raja
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivitybackdoor
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servletsNuha Noor
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESYoga Raja
 
Java Servlet
Java ServletJava Servlet
Java ServletYoga Raja
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySqlDhyey Dattani
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeletonIram Ramrajkar
 
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
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commandsleminhvuong
 

La actualidad más candente (20)

JDBC Tutorial
JDBC TutorialJDBC Tutorial
JDBC Tutorial
 
Jdbc
JdbcJdbc
Jdbc
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
 
Java database connectivity with MYSQL
Java database connectivity with MYSQLJava database connectivity with MYSQL
Java database connectivity with MYSQL
 
JDBC ppt
JDBC pptJDBC ppt
JDBC ppt
 
Database connect
Database connectDatabase connect
Database connect
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
Jdbc in servlets
Jdbc in servletsJdbc in servlets
Jdbc in servlets
 
Jdbc
JdbcJdbc
Jdbc
 
JSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGESJSP- JAVA SERVER PAGES
JSP- JAVA SERVER PAGES
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
Jdbc sasidhar
Jdbc  sasidharJdbc  sasidhar
Jdbc sasidhar
 
Jdbc
JdbcJdbc
Jdbc
 
Best Of Jdk 7
Best Of Jdk 7Best Of Jdk 7
Best Of Jdk 7
 
3 database-jdbc(1)
3 database-jdbc(1)3 database-jdbc(1)
3 database-jdbc(1)
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Advance Java Programs skeleton
Advance Java Programs skeletonAdvance Java Programs skeleton
Advance Java Programs skeleton
 
Ad java prac sol set
Ad java prac sol setAd java prac sol set
Ad java prac sol set
 
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)
 
Executing Sql Commands
Executing Sql CommandsExecuting Sql Commands
Executing Sql Commands
 

Destacado

Types of Drivers in JDBC
Types of Drivers in JDBCTypes of Drivers in JDBC
Types of Drivers in JDBCHemant Sharma
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programmingchhaichivon
 
Andrew_Parker_-_resume3a
Andrew_Parker_-_resume3aAndrew_Parker_-_resume3a
Andrew_Parker_-_resume3aAndrew Parker
 
ABC of Public Relations. Presentation Outline
ABC of Public Relations. Presentation OutlineABC of Public Relations. Presentation Outline
ABC of Public Relations. Presentation OutlineBogdan-Sorin Popescu
 
Dissertation Completed
Dissertation CompletedDissertation Completed
Dissertation CompletedJoel Huskisson
 
Estrutura condicional com Ruby[AULA-2]
Estrutura condicional com Ruby[AULA-2]Estrutura condicional com Ruby[AULA-2]
Estrutura condicional com Ruby[AULA-2]Ricardo Silva
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types pptkamal kotecha
 
Gestion e innovacion educativa ccesa007
Gestion e  innovacion educativa  ccesa007Gestion e  innovacion educativa  ccesa007
Gestion e innovacion educativa ccesa007Demetrio Ccesa Rayme
 

Destacado (18)

Types of Drivers in JDBC
Types of Drivers in JDBCTypes of Drivers in JDBC
Types of Drivers in JDBC
 
Overview Of JDBC
Overview Of JDBCOverview Of JDBC
Overview Of JDBC
 
Jdbc Java Programming
Jdbc Java ProgrammingJdbc Java Programming
Jdbc Java Programming
 
Prativa biswas
Prativa biswasPrativa biswas
Prativa biswas
 
Andrew_Parker_-_resume3a
Andrew_Parker_-_resume3aAndrew_Parker_-_resume3a
Andrew_Parker_-_resume3a
 
CATEAR SERVICES
CATEAR SERVICESCATEAR SERVICES
CATEAR SERVICES
 
ABC of Public Relations. Presentation Outline
ABC of Public Relations. Presentation OutlineABC of Public Relations. Presentation Outline
ABC of Public Relations. Presentation Outline
 
Hizib nashor
Hizib nashorHizib nashor
Hizib nashor
 
Dissertation Completed
Dissertation CompletedDissertation Completed
Dissertation Completed
 
Sivuhyöty 13.10.2016 kasvisivutuote maanparannusaineena
Sivuhyöty 13.10.2016 kasvisivutuote maanparannusaineenaSivuhyöty 13.10.2016 kasvisivutuote maanparannusaineena
Sivuhyöty 13.10.2016 kasvisivutuote maanparannusaineena
 
Teoriascreatividad
TeoriascreatividadTeoriascreatividad
Teoriascreatividad
 
Uudet proteiinilahteet
Uudet proteiinilahteetUudet proteiinilahteet
Uudet proteiinilahteet
 
Estrutura condicional com Ruby[AULA-2]
Estrutura condicional com Ruby[AULA-2]Estrutura condicional com Ruby[AULA-2]
Estrutura condicional com Ruby[AULA-2]
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Perttu Antila, LUKE: Riittääkö metsähaketta kaikille?
Perttu Antila, LUKE: Riittääkö metsähaketta kaikille?Perttu Antila, LUKE: Riittääkö metsähaketta kaikille?
Perttu Antila, LUKE: Riittääkö metsähaketta kaikille?
 
Foresight Friday: Kohti jaettua ymmärrystä työn tulevaisuudesta 3.3.2017
Foresight Friday: Kohti jaettua ymmärrystä työn tulevaisuudesta 3.3.2017 Foresight Friday: Kohti jaettua ymmärrystä työn tulevaisuudesta 3.3.2017
Foresight Friday: Kohti jaettua ymmärrystä työn tulevaisuudesta 3.3.2017
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
Gestion e innovacion educativa ccesa007
Gestion e  innovacion educativa  ccesa007Gestion e  innovacion educativa  ccesa007
Gestion e innovacion educativa ccesa007
 

Similar a JDBC API Guide for Connecting Java to Databases

Similar a JDBC API Guide for Connecting Java to Databases (20)

jdbc_presentation.ppt
jdbc_presentation.pptjdbc_presentation.ppt
jdbc_presentation.ppt
 
Jdbc (database in java)
Jdbc (database in java)Jdbc (database in java)
Jdbc (database in java)
 
JDBC programming
JDBC programmingJDBC programming
JDBC programming
 
Lecture 1. java database connectivity
Lecture 1. java database connectivityLecture 1. java database connectivity
Lecture 1. java database connectivity
 
jdbc
jdbcjdbc
jdbc
 
Chapter Seven- JDBC.pptx
Chapter Seven- JDBC.pptxChapter Seven- JDBC.pptx
Chapter Seven- JDBC.pptx
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
 
JDBC
JDBCJDBC
JDBC
 
Mule jdbc
Mule   jdbcMule   jdbc
Mule jdbc
 
Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)Java DataBase Connectivity API (JDBC API)
Java DataBase Connectivity API (JDBC API)
 
Jdbc tutorial
Jdbc tutorialJdbc tutorial
Jdbc tutorial
 
03-JDBC.pptx
03-JDBC.pptx03-JDBC.pptx
03-JDBC.pptx
 
30 5 Database Jdbc
30 5 Database Jdbc30 5 Database Jdbc
30 5 Database Jdbc
 
Advance Java Programming (CM5I)5.Interacting with-database
Advance Java Programming (CM5I)5.Interacting with-databaseAdvance Java Programming (CM5I)5.Interacting with-database
Advance Java Programming (CM5I)5.Interacting with-database
 
Jdbc
JdbcJdbc
Jdbc
 
Java beans
Java beansJava beans
Java beans
 
PROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part IPROGRAMMING IN JAVA -unit 5 -part I
PROGRAMMING IN JAVA -unit 5 -part I
 
Lecture17
Lecture17Lecture17
Lecture17
 
Final Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.pptFinal Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.ppt
 
Data Access with JDBC
Data Access with JDBCData Access with JDBC
Data Access with JDBC
 

Más de Arati Gadgil (16)

Java adapter
Java adapterJava adapter
Java adapter
 
Java swing
Java swingJava swing
Java swing
 
Java applet
Java appletJava applet
Java applet
 
Java layoutmanager
Java layoutmanagerJava layoutmanager
Java layoutmanager
 
Java awt
Java awtJava awt
Java awt
 
Java stream
Java streamJava stream
Java stream
 
Java thread
Java threadJava thread
Java thread
 
Java networking
Java networkingJava networking
Java networking
 
Java package
Java packageJava package
Java package
 
Java interface
Java interfaceJava interface
Java interface
 
Java inheritance
Java inheritanceJava inheritance
Java inheritance
 
Java eventhandling
Java eventhandlingJava eventhandling
Java eventhandling
 
Java exception
Java exception Java exception
Java exception
 
Java collection
Java collectionJava collection
Java collection
 
Java class
Java classJava class
Java class
 
Java basic
Java basicJava basic
Java basic
 

Último

social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeThiyagu K
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...Pooja Nehwal
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room servicediscovermytutordmt
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesFatimaKhan178732
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...anjaliyadav012327
 

Último (20)

Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Measures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and ModeMeasures of Central Tendency: Mean, Median and Mode
Measures of Central Tendency: Mean, Median and Mode
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...Russian Call Girls in Andheri Airport Mumbai WhatsApp  9167673311 💞 Full Nigh...
Russian Call Girls in Andheri Airport Mumbai WhatsApp 9167673311 💞 Full Nigh...
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
9548086042 for call girls in Indira Nagar with room service
9548086042  for call girls in Indira Nagar  with room service9548086042  for call girls in Indira Nagar  with room service
9548086042 for call girls in Indira Nagar with room service
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Separation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and ActinidesSeparation of Lanthanides/ Lanthanides and Actinides
Separation of Lanthanides/ Lanthanides and Actinides
 
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
JAPAN: ORGANISATION OF PMDA, PHARMACEUTICAL LAWS & REGULATIONS, TYPES OF REGI...
 

JDBC API Guide for Connecting Java to Databases

  • 2. JDBC Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers to connect with the database.
  • 3. API API (Application programming interface) is a document that contains description of all the features of a product or software. It represents classes and interfaces that software programs can follow to communicate with each other. An API can be created for applications, libraries, operating systems, etc
  • 4. JDBCDriver JDBC Driver is a software component that enables java application to interact with the database. There are 4 types of JDBC drivers 1.JDBC-ODBC bridge driver 2.Native-API driver (partially java driver) 3.Network Protocol driver (fully java driver) 4.Thin driver (fully java driver)
  • 5. JDBC-ODBC bridge driver The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.
  • 6. connect to the database Steps 1. Register the driver class 2. Creating connection 3. Creating statement 4. Executing queries 5. Closing connection
  • 7. 1) Register the driver class public static void forName(String className)throws ClassNotFoundException Example Class.forName("oracle.jdbc.driver.OracleDriver");
  • 8. 2)Create the connection object 1) public static Connection getConnection(String url)throws SQLException 2) public static Connection getConnection(String url,String name,String password) throws SQLException Example Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","password");
  • 9. 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. public Statement createStatement()throws SQLException Example Statement stmt=con.createStatement();
  • 10. 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. public ResultSet executeQuery(String sql)throws SQLException Example ResultSet rs=stmt.executeQuery("select * from emp"); while(rs.next()) { System.out.println(rs.getInt(1)+" "+rs.getString(2)); }
  • 11. 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. public void close()throws SQLException Example con.close();
  • 12. DatabaseMetaData Interface DatabaseMetaData interface provides methods to get meta data of a database such as database product name, database product version, driver name, name of total number of tables, name of total number of views etc.
  • 13. Methods public String getDriverName()throws SQLException it returns the name of the JDBC driver. public String getDriverVersion()throws SQLException it returns the version number of the JDBC driver. public String getUserName()throws SQLException it returns the username of the database. public String getDatabaseProductName()throws SQLException it returns the product name of the database. public String getDatabaseProductVersion()throws SQLException it returns the product version of the database. public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types)throws SQLException it returns the description of the tables of the specified catalog. The table type can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.
  • 14. Transaction Transaction represents a single unit of work Properties Atomicity means either all successful or none. Consistency ensures bringing the database from one consistent state to another consistent state. Isolation ensures that transaction is isolated from other transaction. Durability means once a transaction has been committed, it will remain so, even in the event of errors, power loss etc.
  • 15.
  • 16.  Connectioninterface In JDBC, Connection interface provides methods to manage transaction. Methods void setAutoCommit(boolean status) It is true bydefault means each transaction is committed by default. void commit() commits the transaction. void rollback() cancels the transaction.
  • 17. What is JDBC? JDBC stands for Java Database Connectivity, which is a standard Java API for database-independent connectivity between the Java prog ramming language and a wide range of databases. Common JDBC Components DriverManager: This class manages a list of database drivers. Driver: This interface handles the communications with the database server. Connec tion: This interface with all methods for contacting a database. Statement: You use objects created from this interface to submit the SQL statements to the database. ResultSet: These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move throug h its data. SQLException: T his class handles any errors that occur in a database application.
  • 18.
  • 19. JDBC-SQLSYNTAX Structured Query Language (SQL) is a standardized language that allows you to perform operations on a database, such as creating entries, reading content, updating content, and deleting entries. Create Database: The CREAT E DATABASE statement is used for creating a new database. The syntax is: SQL> CREATE DATABASE DATABASE_NAME; Example The following SQL statement creates a Database named EMP: SQL> CREATE DATABASE EMP; Drop Database: The DROP DATABASE statement is used for deleting an existing database. The syntax is: SQL> DROP DATABASE DATABASE_NAME;
  • 20. Create Table: The CREAT E TABLE statement is used for creating a new table. The syntax is: SQL> CREATE TABLE table_name ( column_name column_data_type, ... ); Example: The following SQL statement creates a table named Employees with four columns: SQL> CREATE TABLE Employees ( id INT NOT NULL, age INT NOT NULL, first VARCHAR(255), last VARCHAR(255), PRIMARY KEY ( id ) );
  • 21. INSERT Data: The syntax for INSERT looks similar to the following , where column1, column2, and so on represent the new data to appear in the respective columns: SQL> INSERT INTO table_name VALUES (column1, column2, ...); Example: The following SQL INSERT statement inserts a new row in the Employees database created earlier: SQL> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');
  • 22. SELECT Data: The SELECT statement is used to retrieve data from a database. The syntax for SELECT is: SQL> SELECT column_name, column_name, ... FROM table_name WHERE conditions; The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators. Example The following SQL statement selects the ag e, first and last columns from the Employees table where id column is 100: SQL> SELECT first, last, age FROM Employees WHERE id = 100;
  • 23. The following SQL statement selects the age, first and last columns from the Employees table where first column contains Zara SQL> SELECT first, last, age FROM Employees WHERE first LIKE '%Zara%'; The following SQL statement selects the age, first and last columns from the Employees table where first column contains “a” at end SQL> SELECT first, last, age FROM Employees WHERE first LIKE '%a'; The following SQL statement selects the age, first and last columns from the Employees table where first column contains a at start SQL> SELECT first, last, age FROM Employees WHERE first LIKE 'a%';
  • 24. UPDATE Data: The UPDAT E statement is used to update data. The syntax for UPDATE is: SQL> UPDATE table_name SET column_name = value, column_name = value, ... WHERE conditions; The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators. Example: T he following SQL UPDAT E statement changes the age column of the employee whose id is 100: SQL> UPDATE Employees SET age=20 WHERE id=100;
  • 25. DELETE Data: The DELETE statement is used to delete data from tables. The syntax for DELETE is: SQL> DELETE FROM table_name WHERE conditions; The WHERE clause can use the comparison operators such as =, !=, <, >, <=,and >=, as well as the BETWEEN and LIKE operators. Example: T he following SQL DELET E statement delete the record of the employee whose id is 100: SQL> DELETE FROM Employees WHERE id=100;
  • 26. ImportJDBCPackages import java.sql.* ; // for standard JDBC programs import java.math.* ; // for BigDecimal and BigInteger support Register JDBC Driver try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch(ClassNotFoundException ex) { System.out.println("Error: unable to load driver class!"); System.exit(1); }
  • 27. Create Connection Object: Using a database URL with a username and password: String URL = "jdbc:oracle:thin:@amrood:1521:EMP"; String USER = "username"; String PASS = "password" Connection conn = DriverManager.getConnection(URL, USER, PASS); Closing JDBC connections: conn.close();
  • 28. Statement Use for general-purpose access to your database. Useful when you are using static SQL statements at runtime. T he Statement interface cannot accept parameters. PreparedStatement : Use when you plan to use the SQL statements many times. The PreparedStatement interface accepts input parameters at runtime. CallableStatement : Use when you want to access database stored procedures. The CallableStatement interface can also accept runtime input parameters.
  • 29. Creating Statement Object Before you can use a Statement object to execute a SQL statement, you need to create one using the Connection object's createStatement( ) method, as in the following example: Statement stmt = null; try { stmt = conn.createStatement( ); . . . } catch (SQLException e) { . . . } finally { . . . }
  • 30. Once you've created a Statement object, you can then use it to execute a SQL statement with one of its three execute methods. boolean execute(String SQL) : Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. Use this method to execute SQL DDL statements or when you need to use truly dynamic SQL. int executeUpdate(String SQL) : Returns the numbers of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT , UPDAT E, or DELET E statement. ResultSet executeQuery(String SQL) : Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement.
  • 31. 31 Rowsets Rowsets are the central objects that enable OLE DB components to expose and manipulate data in tabular form. A rowset object is a set of rows in which each row has columns of data. Query processors present query results in the form of rowsets.
  • 32. 32 ResultSet The SQL statements that read data from a database query, return the data in a result set. The SELECT statement is the standard way to select rows from a database and view them in a result set. The java.sql.ResultSet interface represents the result set of a database query. A ResultSet object maintains a cursor that points to the current row in the result set. The term "result set" refers to the row and column data contained in a ResultSet object. The ResultSet interface contains many methods for getting the data of the current row.
  • 33. 33 public int getInt(String columnName) throws SQLException Returns the int in the current row in the column named columnName public int getInt(int columnIndex) throws SQLException Returns the int in the current row in the specified column index. The column index starts at 1, meaning the first column of a row is 1, the second column of a row is 2, and so on. Similarly, there are get methods in the ResultSet interface for each of the eight Java primitive types, as well as common types such as java.lang.String, java.lang.Object, and java.net.URL