JDBC in JAVA
JDBC in JAVA
JDBC Definition
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the
query with the database. JDBC API uses JDBC drivers to connect with the database.
What is API?
API (Application programming interface) is a document that contains a 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
Before JDBC, ODBC API was the database API to connect and execute the query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).
There are 5 steps to connect any java application with the database using JDBC. These steps
are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection
Class.forName("oracle.jdbc.driver.OracleDriver");
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
while(rs.next())
{
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
Creating, reading, updating, and deleting data in a database is a common task in many
applications, and JDBC (Java Database Connectivity) is a Java API that allows you to connect
to a database and perform these operations.
C – Create
R – Read
U – Update
D – Delete
To Create a Table
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
class CRUD
{
}
Output
Successfully connected
Rows inserted = 1
Rows updated = 1
Emp Id : 8, Name : John Doe, Age : 21
Emp Id : 10, Name : James, Age : 31
Rows deleted = 1