asthanegi14 / Java-JDBC

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Java-JDBC

JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query with the database. It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the database.

The java.sql package contains classes and interfaces for JDBC API.
We can use JDBC API to handle database using Java program and can perform the following activities:

  1. Connect to the database
  2. Execute queries and update statements to the database
  3. Retrieve the result received from the database.
  4. Delete data of database.

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:



Step 1. Load the driver
JDBC Driver is a software component that enables java application to interact with the database. 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 mysql Driver: Class.forName("com.mysql.cj.jdbc.Driver");

Note : There are diffrent drivers for diffrent database

Step 2. Create Connection
The getConnection() method of DriverManager class is used to establish connection with the database.
Syntax : Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_Name","Username","password");

Step 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 : Statement stmt=con.createStatement();


Step 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 : ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next()){ System.out.println(rs.getInt(1)+" "+rs.getString(2));}

Step 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 : conn.close();

Thanks for reading

About


Languages

Language:Java 100.0%