Skip to main content

Introduction to JDBC

What is JDBC?

Java Database Connectivity (JDBC) is a Java API that is used to connect and execute queries on a database. It provides a method to connect to a database, execute queries, and retrieve results.

Why do we need JDBC?

In any software application, one of the most common tasks is to interact with a database. This can be for different reasons such as storing user data, fetching user data, updating data, etc. JDBC provides a standardized API for database interaction in Java, which makes it easier to interact with a database.

Components of JDBC

JDBC consists of the following components:

  1. DriverManager: This class manages a list of database drivers. It matches connection requests from the java application with the proper database driver.

  2. Driver: This interface handles the communications with the database server.

  3. Connection: This interface contains all the methods for contacting a database.

  4. Statement: You use objects created from this interface to submit the SQL statements to the database.

  5. ResultSet: These objects contain the result of a query. It acts as an iterator to allow you to move through its data.

Steps to connect to a Database using JDBC

Here are the basic steps to connect any database using JDBC:

  1. Register the Driver: The first step in any JDBC application is to register the driver. We need to initialize the driver to have any interaction with the database.
Class.forName("com.mysql.jdbc.Driver");
  1. Create connection: Next step is to create a connection using the DriverManager class getConnection method.
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/your_database","username","password");
  1. Create Statement: After creating connection, next step is to create Statement object using the createStatement method of the Connection interface.
Statement stmt=con.createStatement();
  1. Execute queries: After creating statement, we can execute any SQL query.
ResultSet rs=stmt.executeQuery("select * from employee");
  1. Process the results: After executing the query, we can process the result.
while(rs.next())  
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));

Conclusion

JDBC is a powerful API that is used to connect Java applications to a wide range of databases. Its ease of use and standardized set of methods make it a great choice for any developer looking to work with databases in Java. The ability to execute SQL queries and process the results also provides a great deal of control over the data.